← Back to JavaScript, page 9

javascript-0168 · Medium mid

What do these closures-in-loops puzzles print, and why do var and let behave differently?

Closures capture variables, not values. A var loop has one shared variable that has reached its final value when the callbacks run, so they all see the same number. A let loop creates a new binding for each iteration, so each callback sees its own copy. The fixes for var code are let, an IIFE or function parameter that copies the value, or forEach and map, whose callbacks get their own parameters.

Full answer

A closure keeps a reference to the variable in the scope where the function was created. It does not copy the value at that moment. That explains the classic puzzle: for (var i = 0; i < 3; i++) setTimeout(() => console.log(i)) prints 3, 3, 3. There is one i for the whole function. The loop finishes first, i is 3, and then the callbacks run and read that one variable.

With let, the specification creates a fresh binding for each iteration and copies the value of the previous iteration into it before the increment runs. So the callbacks see 0, 1, 2. Details worth noting: the copy happens before the update expression (i++), so each closure gets a variable that is not changed by later increments, but a closure can still change its own copy.

Variants and rules:

  • forEach, map, and for...of with const: each call or iteration has a new binding, so they work.
  • for (var i...) { let j = i; fns.push(() => j); } works, since let j is created inside the block on each iteration.
  • An IIFE or a helper function with a parameter copies the value into a new scope: (function (n) {...})(i).
  • setTimeout(fn, 0, i) passes the current value as an argument at the time of the call, which also works.
  • Closures over an object share the object: pushing functions that read obj.count see updates made later.
  • for (let i...) with a closure that changes i inside the body changes the loop counter of that iteration, which then affects the next iteration through the copy step.
  • Closures created in while loops with let declared inside the body have new bindings per pass, but a let declared before the loop is shared.

The deep point: the output depends on when the callback runs and which binding it reads, not on the loop syntax alone. When you explain, name the binding and the moment of reading.

javascript
const run = (label, build) => {
  const fns = build();
  console.log(label.padEnd(36), fns.map((fn) => fn()));
};

run('1. var in a for loop', () => {
  const fns = [];
  for (var i = 0; i < 3; i++) fns.push(() => i);
  return fns;
});
run('2. let in a for loop', () => {
  const fns = [];
  for (let i = 0; i < 3; i++) fns.push(() => i);
  return fns;
});
run('3. var with an IIFE copy', () => {
  const fns = [];
  for (var i = 0; i < 3; i++) (function (n) { fns.push(() => n); })(i);
  return fns;
});
run('4. var with a let copy in the body', () => {
  const fns = [];
  for (var i = 0; i < 3; i++) { let copy = i; fns.push(() => copy); }
  return fns;
});
run('5. forEach callback parameter', () => {
  const fns = [];
  [10, 20, 30].forEach((value) => fns.push(() => value));
  return fns;
});
run('6. let declared before the loop', () => {
  const fns = [];
  let shared = 0;
  for (; shared < 3; shared++) fns.push(() => shared);
  return fns;
});
run('7. closure shares an object', () => {
  const fns = [];
  const counter = { count: 0 };
  for (let k = 0; k < 3; k++) { counter.count++; fns.push(() => counter.count); }
  return fns;
});
run('8. for...in with var', () => {
  const fns = [];
  for (var key in { a: 1, b: 2 }) fns.push(() => key);
  return fns;
});
run('9. for...in with const', () => {
  const fns = [];
  for (const key in { a: 1, b: 2 }) fns.push(() => key);
  return fns;
});
run('10. closure changes its own copy', () => {
  const fns = [];
  for (let i = 0; i < 3; i++) fns.push(() => ++i);
  return fns.concat(fns).slice(0, 4);
});
run('11. increment inside the body', () => {
  const fns = [];
  for (let i = 0; i < 6; i++) { fns.push(() => i); i++; }
  return fns;
});

const results = [];
for (var t = 0; t < 3; t++) setTimeout(() => results.push(['var timeout', t]), 0);
for (let u = 0; u < 3; u++) setTimeout(() => results.push(['let timeout', u]), 0);
for (var w = 0; w < 3; w++) setTimeout((n) => results.push(['argument', n]), 0, w);
setTimeout(() => console.log(results.map(([label, v]) => `${label}:${v}`).join(' ')), 5);

Run with Node.js v24.22.1 as js-168.js; two runs gave identical output. Output: 1. var in a for loop [ 3, 3, 3 ] 2. let in a for loop [ 0, 1, 2 ] 3. var with an IIFE copy [ 0, 1, 2 ] 4. var with a let copy in the body [ 0, 1, 2 ] 5. forEach callback parameter [ 10, 20, 30 ] 6. let declared before the loop [ 3, 3, 3 ] 7. closure shares an object [ 3, 3, 3 ] 8. for...in with var [ 'b', 'b' ] 9. for...in with const [ 'a', 'b' ] 10. closure changes its own copy [ 1, 2, 3, 2 ] 11. increment inside the body [ 1, 3, 5 ] var timeout:3 var timeout:3 var timeout:3 let timeout:0 let timeout:1 let timeout:2 argument:0 argument:1 argument:2

Key points

  • Closures capture variables, not values; a var loop has one shared variable.
  • let creates a new binding per iteration, copied from the previous one.
  • Fixes: let, a block-scoped copy, an IIFE or parameter, forEach or map, or passing an argument to setTimeout.
  • Objects captured by closures are shared and show later changes.
  • A let declared before a loop is shared; one declared inside the body is per pass.

Common mistakes

  • Explaining the var result as the value being copied late, instead of one shared variable.
  • Using var in loops that create callbacks.
  • Assuming let creates a new variable only when you declare it inside the body.
  • Capturing a mutable object and expecting a snapshot.

Follow-ups

  • How does the specification copy the let binding between iterations?
  • Why does for...of with const work even though const cannot change?
  • How would you fix the var version without changing the loop to let?

Tips

  • Say closures capture variables, then name which variable each callback reads.
  • Give two fixes: let, and passing an argument.
  • Mention that timing matters: the loop ends before the callbacks run.