var variable = "top level " ;
function outer(){
alert(variable); // why does this alert returns undefined ??
var variable = " inside outer, outside inner";
function inner(){
alert(variable);
}
inner();
}
outer();
What I understood from the definition of lexical scoping is that, the functions can access all the values in and above their scope i.e. everything defined before them. So why does the first alert returns undefined ?
It's because of hoisting, the variable you've declared inside the function is hoisted to the top of the scope it's in, so your code really looks like this
var variable = "top level " ;
function outer(){
var variable; // undefined, a new local variable is declared, but not defined
alert(variable); // alerts undefined, as that's what the variable is
variable = " inside outer, outside inner";
function inner(){
alert(variable);
}
inner();
}
outer();
If you just wanted to change the outside variable, drop the var keyword, as that declares a new local variable instead
var variable = "top level " ;
function outer(){
alert(variable);
variable = " inside outer, outside inner"; // no "var"
function inner(){
alert(variable);
}
inner();
}
outer();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With