Why are they similar in this case?
Because var
is hoisted (but not set), like a function declaration is hoisted, meaning that there is an a
in the local scope before a = 10;
is evaluated, so the global a
never gets modified - the identifier lookup finds the local a
first so sets that
Related parts of the other question
var a = 1;
function b() {
a = 10;
return;
function a() {}
}
b();
alert(a);
Why is a === 1
?
That the answer was trying to say was that b
is equal to
function b() {
function a() {}
a = 10;
return;
}
Similar to
function b() {
var a = function () {};
a = 10;
return;
}
i.e. there is an identifier a
defined in b
, so
function b() {
var a = 10;
return;
}
And now, obviously, the global a
will not be modified by b
Please note that the position of the var
isn't really important, just that it's there, the following will produce the same behaviour
function b() {
a = 10;
return;
var a;
}