var a = 123;
function f() {
alert(a);
var a = 1;
alert(a);
}
f();
This outputs - first "undefined" and then "1". Why is it so? Why it is
outputting "undefined" in the first alert even though global variable
"a" is defined.
Think of your code as being written this way, because this is what is
happening inside a [hypothetical] Javascript engine.
(Note: While the actual internals of HOW the engine works may vary, it
will produce the same results that this code does... variables created
as the first thing the function does, any assignment deferred to the time
where the assignment happens.)
var a = 123;
function f() {
// ALL variables that get declared in the function are created first,
// regardless of where the 'var' keyword appears. This is why one can
// re-declare the variable without error (though JSLint will catch it).
var a;
alert(a); // a is undefined.
a = 1; // The assignment happens here. Remember, the variable
// was created coming into the function.
alert(a); // And now a has a value.
}
f();