JavaScriptFundamental (ES6), part 1
Why var in a for loop closure fails in JavaScript
4 Why var in a loop closure gives the wrong answer
fairBuild three functions in a loop that each return the counter, once with var and once with let. Explain the difference, then show the fix people used before let existed.
Stuck? Three hints, smallest first
- 1. A
varcounter is one variable for the whole loop, so all three closures read the same slot. - 2.
letin aforheader creates a fresh binding per iteration, copied at the top of each turn. - 3. The old fix was to pass the value into an immediately-invoked function, which gives each iteration its own parameter.
function withVar() {
const out = [];
for (var i = 0; i < 3; i++) out.push(() => i);
return out.map((f) => f());
}
function withLet() {
const out = [];
for (let i = 0; i < 3; i++) out.push(() => i);
return out.map((f) => f());
}
function withIife() {
const out = [];
for (var i = 0; i < 3; i++) {
((n) => out.push(() => n))(i);
}
return out.map((f) => f());
}
function overAnIterable() {
const out = [];
for (const stop of ['Yaba', 'Mushin']) out.push(() => stop);
return out.map((f) => f());
}
function varAfterTheLoop() {
for (var i = 0; i < 3; i++);
return i;
}
function letAfterTheLoop() {
for (let i = 0; i < 3; i++);
try { return i; } catch (e) { return e.constructor.name; }
}
const distinct = (() => {
const fns = [];
for (var j = 0; j < 2; j++) fns.push(() => j);
return fns[0] === fns[1];
})();
console.log('var :', withVar(), '<- the loop finished, i is 3, all three read it');
console.log('let :', withLet());
console.log('iife:', withIife());
console.log('of :', overAnIterable());
console.log('i after a var loop:', varAfterTheLoop(), ' after a let loop:', letAfterTheLoop());
Output
7 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 7 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('var captures one shared binding, so every closure reads the final value', withVar(), [3, 3, 3]);
test('let makes a fresh binding each turn', withLet(), [0, 1, 2]);
test('the pre-let fix was an IIFE per iteration', withIife(), [0, 1, 2]);
test('for...of with const behaves like let', overAnIterable(), ['Yaba', 'Mushin']);
test('a var counter is still readable after the loop', varAfterTheLoop(), 3);
test('a let counter is not', letAfterTheLoop(), 'ReferenceError');
test('the closures are distinct functions either way, they only share a variable', distinct, false);
Three closures, one variable. The loop runs to completion before any of them is called, i is 3 by then, and all three report 3 — the last assertion makes it clear the functions themselves are separate objects, so the problem is the variable, not the function.
let in a for header is special-cased in the specification: a new binding is created for each iteration and seeded with the previous value. That is why [0, 1, 2] falls out with no extra work, and why the IIFE wrapper is now only of historical interest.