I came across JavaScript 'hoisting' and I didn't figure out how this snippet of code really functions:
var a = 1;
function b() {
a = 10;
return;
function a() {}
}
b();
alert(a);
I know that function declaration like ( function a() {}
) is going to be hoisted to the top of the function b
scope but it should not override the value of a
(because function declarations override variable declarations but not variable initialization) so I expected that the value of the alert would be 10 instead of 1!!
a
is set to 1
b()
is calledfunction a() {}
is hoisted and creates a local variable a
that masks the global a
a
is set to 10
(overwriting the function a
)a
(still 1
) is alerted