BonsaiDen / JavaScript-Garden

A collection of documentation about the most quirky parts of the JavaScript language.
http://bonsaiden.github.com/JavaScript-Garden
MIT License
3.45k stars 559 forks source link

Mistake in "scopes and namespaces" #379

Closed FokinAleksandr closed 6 years ago

FokinAleksandr commented 6 years ago

...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

peterjwest commented 6 years ago

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);
peterjwest commented 6 years ago

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