问题
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