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.