Search code examples
javascriptvar

Why is this simple code from JavaScript incorrectly variable hoisting?


I'm trying to understand JavaScript variable hoisting and I'm getting confused with the documentation specified by Mozilla.

The documentation which I am referring to is here:

console.log(x === undefined); // true
var x = 3;

I am using the developer's console on Google Chrome to test this code which is on the latest version. When I execute the above code, I get returned false when the Mozilla documentation states that it should be returned true.

code example

This output above means that x is definitely being set to 3 before console.log() is run. Is this documentation specified by Mozilla incorrect or is there something I'm not understanding here?


Solution

  • It will return true the first time you run it, because x starts out as undefined. After you run
    var x = 3, x gets set to 3, so the next time you run the console.log(x === undefined) comparison it returns false, as x is no longer undefined.