1st test:
var a = 1;
function b() {
a = 10;
return;
function a() {}
}
b();
alert(a); // 1
2nd test:
var a = 1;
function b() {
a = 10;
return;
}
b();
alert(a); // 10
In the first test, a
is equal to 1
, although I set it to 10
in the method. In the second test, I set it to 10
and it is set to 10
when I output it.. How does this work?
The function declaration function a() {}
declares a variable name a
in the local scope of your b
function (and assigns it the function). When you are assigning to a
, you will assign to that local variable not the global one.
With hoisting applied, your code is equivalent to
var b = function b() {
var a = function a() {};
a = 10;
return;
}
var a = 1;
b();
alert(a); // 1, obvious now
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With