BonsaiDen/JavaScript-Garden

Mistake in "scopes and namespaces"

FokinAleksandr opened this issue · 2 comments

...The above code gets transformed before execution starts. JavaScript moves the var statements, as well as function declarations, to the top of the nearest surrounding scope....

Then in the code snippet we see that vars are above function declarations.

Functions get placed above vars.
For example if
var x = 1; function x() {}; console.log(x);
then 1 is logged

Actually it's the other way round.
In your example the variable and function declarations get hoisted, but the assignment does not, so the answer is 1:

var x = 1; 
function x() {}; 
console.log(x);

Becomes:

var x; 
function x() {}; 
x = 1; 
console.log(x);

If there was no assignment, then the function declaration would win:

var x;
function x() {}; 
console.log(x);

Becomes:

var x; 
function x() {}; 
console.log(x);

This second example is the same regardless of the order of var x; and function x() {};