Local Variable Impact Global Variable - Javascript Variable Scoping
Solution 1:
In javascript, variable declarations are 'hoisted' to the top of the function, independant of where you declared them.
So in the first variation of changeGlobal, when you declared var a = "local"
, the a
variable declaration is hoisted up to the top. The assignment of the variable doesn't get hoisted as well, so at the point when you alert a
, its an unassigned variable, hence undefined.
That is,
function changeGlobal(){
alert(a); //why is 'a' undefined here?if(a){
var a = "local";
alert(a);
}
}
is equivalent to
function changeGlobal(){
var a; // hoisted here (not assigned a value yet)
alert(a); //why is 'a' undefined here?if(a){
a = "local"; // only assigned a value here
alert(a);
}
}
Solution 2:
In version 1 you declare a local variable named a
that takes precedence over the global a
within the changeGlobal
function. Even though it's defined after the alert(a);
call, its definition is 'hoisted' up to the beginning of the scope, but isn't initialized until the var a = "local";
line. That's why the alert(a);
shows undefined
.
In version 2, because there isn't a local a
, you're always dealing with the global a
which is already initialized before the function runs.
Solution 3:
JavaScript has lexical scoping, where a variable can be dereferenced from the program/function where it was var
ed, and down (as in, referencing it will not throw a ReferenceError
.
The var
statements will also be hoisted, and the initial value set to undefined
.
Or in layman terms, variables are scoped to the function they are defined in, and all variables are available at any point during the functions execution although a value might not be assigned yet.
Combined, this is what you are observing - a local var shadowing the global var.
Post a Comment for "Local Variable Impact Global Variable - Javascript Variable Scoping"