According to Benn Flynn's comment, the parser pre-scans and / or compiles the code before actually executing it. Therefore, it detects the scope of the variable from any line, executed or not, in your block.
Run this in your browser console:
var f = function() {
In the console, you will see something like this:
1 undefined
And then window.x does not exist. It is not mentioned anywhere, thanks to our declaration - whether a part of the declaration is needed, I'm not sure. It should not be. But I won’t be surprised to find out that some version of IE ignores the declaration if the destination is also not present.
Compare this to this:
var f = function() { x = 1; console.log(x, window.x); return; x = 2;
We see this in the console:
1 1
And after that windows.x has 1 .
It is also noteworthy that definedAfter() works correctly because it is not written in the form of a variable assignment:
Instead, it is written in the form of a “declarative function” that fails to be “executed”.
function definedAfter() { }
Rather, the compiler sees this at compile time and says, “Oh, this function is part of the scope.” This difference gives you the ability to precisely control when your functions are available in the variable assignment syntax. And in a declarative form, the ability to define your functions anywhere without worrying about the execution order.
source share