Javascript hoisting confusion

时间:2016-08-31 17:52:34

标签: javascript hoisting

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.

1 个答案:

答案 0 :(得分:1)

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.

相关问题