-1

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.

Kranthi
  • 1,377
  • 1
  • 17
  • 34
  • The standard ES5 JavaScript grammar [does not allow function declarations inside blocks](http://stackoverflow.com/questions/25111087/why-is-a-function-declaration-within-a-condition-block-hoisted-to-function-scope). The ability to parse this code requires an extension of the standard grammar, and the execution behavior differs between ES5 implementations. I am not sure what the current stance is in the latest specification. – apsillers Aug 31 '16 at 18:01
  • Before ES6, function declarations inside blocks was undefined behavior. Chrome and Firefox behaved differently (maybe they still do). In ES6, those are not supposed to be hoisted anymore I believe. – Felix Kling Aug 31 '16 at 18:01
  • Lol, don't ever write that again. My eyes hurt just looking at it. :) – mattdevio Aug 31 '16 at 18:02
  • You've written the code. Why have you not just tried it? If you had, you could have a better/different understanding and asked a more directed question (or better yet done some searching to see if you could find [an answer](http://stackoverflow.com/a/4071439/3773011), or [two](http://stackoverflow.com/questions/25111087/why-is-a-function-declaration-within-a-condition-block-hoisted-to-function-scope)). – Makyen Aug 31 '16 at 18:03
  • I tried it, without trying I never post a question. More over I wanted to understand and so asked the community. Anyways thanks alot! – Kranthi Aug 31 '16 at 18:05

1 Answers1

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.

Liam Egan
  • 407
  • 2
  • 11