JavaScript hoisting and scope

后端 未结 1 929
傲寒
傲寒 2021-01-25 18:07

why the foo() function logs undefined? The first text variable is a global variable so foo() should have an access to it.

         


        
相关标签:
1条回答
  • 2021-01-25 18:34

    Even though the var statement is after the console.log() statement, the declaration is hoisted to the beginning of the function. So this declares a local variable that shadows the global variable. But the initialization doesn't happen until you actually get to the statement, which is after the console.log() statement.

    So your function is equivalent to:

    function foo() {
        var text;
        console.log(text);
        text = 'inside';
    }
    

    If you didn't use the var declaration then you would continue to use the global variable, and the reassignment wouldn't happen until after the console.log().

    0 讨论(0)
提交回复
热议问题