JavaScript hoisting and scope

2019-03-06 01:54发布

问题:

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

var text = "outside";

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

foo();

回答1:

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().