Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If statement and variable hoisting

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 Answers

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.

like image 79
Paul Avatar answered May 05 '26 21:05

Paul