Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 1

Closures in loops: var vs let in JavaScript

144 a closure in a loop, var against let

fair

Build an array of functions inside a for loop, once with var as the counter and once with let, then call them all and report the two different result arrays. Reproduce the let behaviour with an IIFE, show what for...of does with each keyword, say what survives after the loop, and find out what happens to that iteration binding if the body itself changes the counter.

Stuck? Three hints, smallest first
  1. 1. var gives the whole function ONE variable. Three closures over one variable can only ever report one value.
  2. 2. let in a for header is special-cased: the loop creates a fresh binding per iteration and copies the last value into it.
  3. 3. The pre-let fix was to make a new scope by hand, so pass the counter into a function that returns the closure.

The answer

const withVar = [];
for (var i = 0; i < 3; i++) withVar.push(() => i);

const withLet = [];
for (let j = 0; j < 3; j++) withLet.push(() => j);

const withIife = [];
for (var k = 0; k < 3; k++) withIife.push(((frozen) => () => frozen)(k));

const withForEach = [];
[0, 1, 2].forEach(function (n) { withForEach.push(() => n); });

const called = [withVar.map((f) => f()), withLet.map((f) => f()), withIife.map((f) => f()), withForEach.map((f) => f())];

const afterVar = i;
let afterLet;
try { afterLet = j; } catch (e) { afterLet = e.constructor.name; }

const varOf = [];
for (var v of ['a', 'b', 'c']) varOf.push(() => v);
const constOf = [];
for (const w of ['a', 'b', 'c']) constOf.push(() => w);

// The body mutates the counter. Which binding did the closure capture?
const nudged = [];
const bodySaw = [];
for (let m = 0; m < 3; m++) { nudged.push(() => m); bodySaw.push(m); m += 10; }

console.log('var / let :', called[0], called[1]);
console.log('iife/each :', called[2], called[3]);
console.log('after     :', afterVar, afterLet);
console.log('for...of  :', varOf.map((f) => f()), constOf.map((f) => f()));
console.log('nudged    :', nudged.map((f) => f()), '| body saw:', bodySaw);

Output


      
8 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 8 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

8 checks

test('three closures over one var see the value that ended the loop', called[0], [3, 3, 3]);
test('three closures over a per-iteration let see three values', called[1], [0, 1, 2]);
test('an IIFE reproduces let by making a scope by hand', called[2], [0, 1, 2]);
test('forEach never had the bug: each call has its own parameter', called[3], [0, 1, 2]);
test('the var counter outlives the loop at 3; the let counter does not exist', [afterVar, afterLet], [3, 'ReferenceError']);
test('for...of is no exemption: var repeats the last item, const does not', [varOf.map((f) => f()), constOf.map((f) => f())], [['c', 'c', 'c'], ['a', 'b', 'c']]);
test('a body that adds 10 to the counter ends the loop after one pass', [nudged.length, bodySaw], [1, [0]]);
test('and that closure reports 10, not the 0 the body saw, because they share the binding', nudged.map((f) => f()), [10]);

A closure captures a binding, never a value. That one sentence is the whole exercise. var declares one function-scoped binding, so all three functions point at the same box, and by the time anyone calls them the box holds 3 — the value that failed the loop test. let in a for header gets special treatment in the spec: each iteration creates a fresh binding, the previous value is copied in, and the update expression runs against the new one. Three iterations, three boxes, three answers.

The last two assertions show the copying being real rather than a metaphor. The body sets m to 10, so m++ makes 11 in the next iteration copy, the test fails and the loop stops after one pass — the body only ever saw 0. Yet the captured closure reports 10, because it holds iteration one binding and the body mutated exactly that binding. A value snapshot would have said 0; a shared binding says 10.

Classically this bug appeared with setTimeout inside a loop, all callbacks reporting the final index. Pushing closures into an array shows the same thing with no asynchrony at all, which is the honest framing: nothing about it is about timing. Three fixes exist and two are still worth knowing — let, and an iterator method like forEach or map whose parameter is a fresh binding per call. The IIFE is the museum piece.

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.