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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With