Question

I have a global variable i which I increment (see fiddle here):

(function increment() {
   i += 1;   
})();

i = 0;

​In Chrome, I get the error Uncaught ReferenceError: i is not defined.

Shouldn't the variable i be hosted here, so that inside the function increment, the variable i is defined as undefined?

Était-ce utile?

La solution

Variable declaration statements are hoisted. You have no declaration.

A declaration statement uses var to declare the variable. Since you haven't declared it, all you have is the assignment expression, which implicitly creates the global variable at the time of the expression evaluation.

In other words, no formal declaration means no hoisting.


Now let's say you did formally declare it, allowing the variable declaration to be hoisted. The operation inside the IIFE would result in NaN, but would be overwritten by the later assignment of 0.

This is because only the declaration is hoisted, not the assignment.

// The 'var i' part below is actually happening up here.

(function increment() {
   i += 1;   // "i" is declared, but not assigned. Result is NaN
})();

var i = 0; // declaration was hoisted, but the assignment still happens here

console.log(i); // 0
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top