This is me This is me - 3 months ago 9
Javascript Question

Javascript hoisting confusion

I read Kyle's

I don't know JS
and came to know that function declarations will
hoist
first before the
var
. So in the below code

<script>
foo();
var a = true;
if ( a ) {
function foo() { console.log( "a" ); }
}else {
function foo() { console.log( "b" ); }
}

foo();
</script>


foo should be hoisted first and should print "b" as output for the first foo(), right? or am I missing anything?

Explanation or a link to understand to the code and hoisting in different scenario's would be a great help.

Answer

Hoisting (in the way that you're expecting here) will only work when there is a precedential order of things that is unambiguous. In this case, because your function is defined inside an if block, hoisting it will not happen as you expect it to.

This will work:

  foo();
   var a = true;
   function foo() { console.log( "a"  );  }

   foo();

Because it removes from the equation your if statement.

Comments