Reputation: 15626
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
?
Upvotes: 3
Views: 197
Reputation: 50905
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
, alert
s it, and then re-sets its value to 9
.
At the time of the alert
, its value is undefined
because of the hoisting.
Upvotes: 8
Reputation: 12170
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?
Upvotes: 0