3
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 ?

JasonMArcher
  • 14,195
  • 22
  • 56
  • 52
voodoo
  • 31
  • 1

1 Answers1

3

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();
adeneo
  • 312,895
  • 29
  • 395
  • 388