Sub topic 9
Loops, Closures, and the Classic var Bug
This chapter assumes you know how var is function-scoped and how let and const are block-scoped (covered in earlier chapters). You should also be comfortable writing arrow functions and calling array methods such as map.
A closure is a function that remembers the variables from the scope where it was created. A closure keeps a live reference to the variable itself, not a copy of its value. Combine that with a loop and var, and you get one of the best-known bugs in JavaScript.
The Bug
The loop below builds three functions, and each one returns the loop counter:
const withVar = [];
for (var i = 0; i < 3; i++) {
withVar.push(() => i);
}
console.log(withVar.map(f => f())); // [3, 3, 3]Most people expect [0, 1, 2]. The output is [3, 3, 3] because var i is scoped to the enclosing function (or the global scope), not to the loop. The whole loop has a single i binding. All three arrow functions close over that same binding. By the time any of them runs, the loop has finished and i holds 3, the value that made i < 3 false.
The same thing happens with asynchronous callbacks, which is where the bug usually turns up in real code:
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 0); // logs 3, 3, 3
}The callbacks run after the loop completes, so each one reads the final value.
The Fix: let
Swap var for let and the behavior changes:
const withLet = [];
for (let j = 0; j < 3; j++) {
withLet.push(() => j);
}
console.log(withLet.map(f => f())); // [0, 1, 2]A for loop with a let declaration in its header gets special treatment from the language. Each iteration creates a fresh binding for j and initializes it with the value from the end of the previous iteration. Then j++ runs on that new binding. Each closure captures a different binding, so each one remembers a different value.
Pre-ES2015 Workarounds
Before let existed, developers forced a new scope on each iteration with an immediately invoked function expression (IIFE), which passed the current value in as a parameter:
const fns = [];
for (var i = 0; i < 3; i++) {
(function (n) {
fns.push(() => n);
})(i);
}
console.log(fns.map(f => f())); // [0, 1, 2]Each call to the IIFE creates a new function scope with its own n. You will still find this pattern in older codebases. In new code, let does the same job more clearly.
Array iteration methods avoid the problem too, because every callback invocation gets its own parameter binding:
const fromForEach = [];
[0, 1, 2].forEach(n => fromForEach.push(() => n));
console.log(fromForEach.map(f => f())); // [0, 1, 2]const in Loops
Each iteration of a for...of or for...in loop creates a new binding, and the loop never reassigns it. That makes const a good choice there:
const handlers = [];
for (const name of ['a', 'b', 'c']) {
handlers.push(() => name);
}
console.log(handlers.map(f => f())); // ['a', 'b', 'c']Common Errors
| Symptom | Cause | Fix |
|---|---|---|
| Every callback sees the final loop value | `var` counter shared by all closures | Declare the counter with `let` |
| `TypeError: Assignment to constant variable` in a loop | `const` counter in a classic `for` loop | Use `let` for the counter |
| Bug persists after switching to `let` | Counter declared with `let` outside the loop header | Declare it inside the `for (...)` header |
That last row matters. The per-iteration binding only happens when the variable is declared in the loop header. Code like let k; for (k = 0; k < 3; k++) still has a single shared binding.
Exercise
What does this code log, and why? let k; const out = []; for (k = 0; k < 3; k++) { out.push(() => k); } console.log(out.map(f => f()));
Show answer
It logs [3, 3, 3]. Because k is declared outside the loop header, there is only one binding for k, and every closure reads its final value of 3. To get [0, 1, 2], move the declaration into the header: for (let k = 0; k < 3; k++).
Exercise
Rewrite for (var i = 0; i < 3; i++) { setTimeout(() => console.log(i), 0); } so it logs 0, 1, 2, using one keyword change.
Show answer
Change var to let: for (let i = 0; i < 3; i++) { setTimeout(() => console.log(i), 0); }. Each iteration gets its own i binding, so each callback logs the value from its own iteration.