0

Based on my current knowledge, I faced something really unexpected in Javascript. Consider this simple code:

foo();
if(true){
  function foo(){
    console.log(i);
  }
}
foo();

I know that variable and function declarations will be hoisted by the Js engine at the creation phase. In this example the function foo will be hoisted and when creation phase is done. The engine will start to run the code line by line, at the first line of the code a function called foo should be invoked. We have that function, because it was hoisted before right? the problem is here a TypeError will be thrown which says that foo is not a function. And when I remove the if block everything works well. I think it's somehow related to the block scopes but don't know how exactly and why it behaves like this.

What's going on here?

I know that function declarations should not be placed in blocks.

Peshrow
  • 11
  • 3
  • 1
    "*I know that function declarations should not be placed in blocks.*" - then don't do it :-) Also make sure to use strict mode. – Bergi Mar 30 '22 at 10:26
  • "*What's going on here?*" - the block scope has its own creation phase. – Bergi Mar 30 '22 at 10:26
  • @Bergi `then don't do it`, I assume this is only if inside a loop these days, or if you really do have to target ES5. – Keith Mar 30 '22 at 10:39
  • @Keith Yeah, I was trying to be quippy. Actually I'm all for declaring functions in block scopes where it makes sense. The advice should be to "*…then don't try to call it outside of that block*", really. – Bergi Mar 30 '22 at 10:49

0 Answers0