Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lexical Scoping in javascript function, why is the code returning undefined [duplicate]

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 ?

like image 432
voodoo Avatar asked Aug 02 '26 00:08

voodoo


1 Answers

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();
like image 86
adeneo Avatar answered Aug 04 '26 15:08

adeneo