I execute function like this:
var a = 123;
function f() {
alert(a);
var a = 9;
}
f();
the result is undefined, why this happened? Why it's not 123?
Your function is actually compiled as:
function f() {
var a;
alert(a);
a = 9;
}
because of variable hoisting: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Statements/var#var_hoisting
So your function redeclares a as a local variable with the value as undefined, alerts it, and then re-sets its value to 9.
At the time of the alert, its value is undefined because of the hoisting.
var a = 9;, the alert could show correctly 123, why it doesn't redeclares a?var a = 9;, then there is no redeclaration...you removed it...all your function will be is alert(a);. So it looks up the scope chain and finds a in the global scope as 123, so it's evaluated as 123.alert, so this means the variable declare is doesn't matter with exetute order?a is technically redefined at the beginning of the function (before the alert)If you declare a in a function syntax again that becomes a new variable. If you want to use the previous value 123 then you should not have included the var a = 9 statement, since it creates a new variable.
This may explain in detail :
What is the scope of variables in JavaScript?
ais defined within the scope off, just not at the point where you callalert(). Henceundefined.