Nathan Hall
Nathan Hall

Reputation: 127

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?

Upvotes: 1

Views: 77

Answers (2)

mohammad
mohammad

Reputation: 86

i run it in Mozilla and chrome and it is true: for first time the answer is true because it is not defined but will be wrong in next time. the answer does not change by clearing the console and you must restart browser.

Upvotes: 0

Obsidian Age
Obsidian Age

Reputation: 42334

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.

Upvotes: 2

Related Questions