If statement and variable hoisting

﹥>﹥吖頭↗ 提交于 2019-12-07 20:16:24

问题


I am learning about variable hoisting in JavaScript, and found this behavior weird:

var x = 0;

(function () {
    //Variable declaration from the if statement is hoisted:
    //var x; //undefined

    console.log(x); //undefined

    if (x === undefined) {
        var x = 1; //This statement jumps to the top of the function in form of a variable declaration, and makes the condition become true.
    }
}());

Is it correct, that in this case, the statement makes the condition true so it can be executed?


回答1:


Hoisting hoists only the declaration, but not the assignment. Your code is equivalent to:

var x = 0;

(function () {
    //Variable declaration from the if statement is hoisted:
    var x;

    console.log(x); //undefined

    if (x === undefined) {
        x = 1;
    }
}());

The if statement's condition expression evaluates to true and x = 1 is reached.




回答2:


By the way ,if you declare a variables in a if statement ,No matter the if condition pass or not pass,the declaration is always hosited.For example:

console.log(a); //undefined , not respond ReferenceError ,it has been hoisted
if(true){
  var a=1;
}
console.log(b); //same as above
if(false){
  var b=1;
}


来源:https://stackoverflow.com/questions/34149693/if-statement-and-variable-hoisting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!