This is me This is me - 1 year ago 108
Javascript Question

Javascript hoisting confusion

I read Kyle's

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

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


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 Source

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:

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


Because it removes from the equation your if statement.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download