Possible Duplicate:
variable hoisting
var a = "global";
//version 1
function changeGlobal(){
alert(a); //why is 'a' undefined here?
if(a){
var a = "local";
alert(a);
}
}
//version 2
function changeGlobal(){
alert(a); //why is 'a' 'global' here? what diff does 'var a="local"' make?
if(a){
//var a = "local";
alert(a);
}
}
changeGlobal();
Question are inline. Help me understand variable scoping.
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", theavariable declaration is hoisted up to the top. The assignment of the variable doesn’t get hoisted as well, so at the point when you alerta, its an unassigned variable, hence undefined.That is,
is equivalent to