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?
Variable declaration statements are hoisted. You have no declaration.
A declaration statement uses
varto 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 of0.This is because only the declaration is hoisted, not the assignment.