Can anybody break down for me into steps how this (it looks simple in the first place) is interpreted by the browser:
var a = 1;
function b() {
a = 10;
function a() {}
}
b();
alert(a);
it will bring 1
. If I would change a function name to anything else, etc:
var a = 1;
function b() {
a = 10;
function m() {}
}
b();
alert(a);
it will alert 10
.
The scope of a variable declared with var
is the entire function in which it is declared, it doesn't start at the point of declaration. It's often described as variable declaration hoisting and can be seen as a move of all variable declarations to the start of the function. For function definitions, both the declaration and the "assignement" are moved together.
function b() {
a = 10;
function a() {}
}
is equivalent to
function b() {
var a = function() {};
a = 10;
}
which means you declare a new variable a
, and the a = 10
statement only changes the internal variable a
, not the external one. We say the internal variable a
shadows the external one.
In the second case, there's no variable a
in the internal scope, which means the external one is used and changed (when looking for a variable, you go from the internal scope to the most external one following the closure chain).
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