I've been learning Javascript using Object-Oriented JavaScript by Stoyan Stefanov
He offers an example comparing global and local scope:
var a = 123;
function f() {
alert(a);
var a = 1;
alert(a);
}
f();
Looking at this example, I expected the first alert to be '123' and the second alert to be '1'. Lo and behold, Stoyan says:
You might expect that the first alert() will display 123 (the value of
the global variable a) and the second will display 1 (the local a).
This is not the case. The first alert will show “undefined”. This is
because inside the function the local scope is more important than the
global scope. So a local variable overwrites any global variable with
the same name. At the time of the first alert() a was not yet defined
(hence the value undefined) but it still existed in the local space.
The explanation was not clear to me, how can the local variable overwrite the global variable in the first alert? Any other/different explanations would be appreciated.
Answer
It is not overriding the global variable. What is happening is called "variable hoisting". That is, a var a;
gets inserted at the top of the function.
The script engine changes your script to be the following:
var a = 123;
function f() {
var a;
alert(a);
a = 1;
alert(a);
}
f();
Lesson to learn: Always declare your variables before you use them. Some will say declare all your variables at the top of the function.
No comments:
Post a Comment