Why is a global variable undefined?

It took me some time to debug a script in which a global variable was undefined in a function, as I thought it was due to closures or other scope-related things. But the real cause was simple: if a global variable is re-declared as local in a function, then it is undefined in the local scope before its second declaration.

var x=1;

function myfunc(){
alert(x); // shows "1"
}

function myfunc2(){
if(typeof(x)==='undefined'){
// this will execute as "x" is undefined here
}
var x=2;
alert(x); // shows "2"
}

Popular Posts