Sub topic 12
The Classic Loop Closure Bug
This chapter assumes you already know how closures capture their surrounding scope. It also assumes you know that var is function-scoped and let is block-scoped. Here we combine those ideas to explain one of the most common bugs in JavaScript.
The Symptom
You create several functions inside a loop. You expect each one to remember the loop counter from its own iteration. Instead, every function reports the same final value.
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log("var:", i), 0);
}
// var: 3
// var: 3
// var: 3The loop finishes before any callback runs. When the callbacks finally run, they all read i, and i is now 3.
Why It Happens: One Binding, Many Closures
A closure captures a variable, which is a binding in a scope. It does not capture the value the variable held at the moment the closure was created. With var, the loop counter is declared once in the enclosing function or script scope. Every iteration updates that same binding, so all three arrow functions point at one shared i.
const withVar = [];
for (var i = 0; i < 3; i++) {
withVar.push(() => i);
}
console.log(withVar.map(f => f())); // [3, 3, 3]The Fix: let Creates a Binding per Iteration
When a for loop header uses let, the language creates a fresh binding for each iteration. It copies the current value into the new binding before running the increment. Each closure therefore captures a different variable.
const withLet = [];
for (let j = 0; j < 3; j++) {
withLet.push(() => j);
}
console.log(withLet.map(f => f())); // [0, 1, 2]Older Fixes You Will Still See
Code written before ES2015 had no let. It created a new function scope for each iteration with an immediately invoked function expression (IIFE):
var callbacks = [];
for (var i = 0; i < 3; i++) {
(function (captured) {
callbacks.push(function () { return captured; });
})(i);
}
console.log(callbacks.map(f => f())); // [0, 1, 2]Each call to the IIFE has its own captured parameter, so each closure gets its own binding. Array methods like forEach work for the same reason: the callback runs once per element, and each call has a separate parameter scope.
const fns = [];
[0, 1, 2].forEach(n => fns.push(() => n));
console.log(fns.map(f => f())); // [0, 1, 2]Common Mistakes
| Mistake | Result | Fix |
|---|---|---|
| `var` counter with async callbacks | All callbacks see the final value | Use `let` in the loop header |
| `let i` declared outside the loop | One shared binding, same bug | Declare `let` inside the `for` header |
| Using `const` in a classic `for` header | `TypeError` when `i++` runs | Use `let`, or `const` in `for...of` |
| Capturing a mutable object | Closures see later mutations | Copy the value into a per-iteration variable |
Exercise
What does this code log, and why? let k = 0; const out = []; for (; k < 3; k++) { out.push(() => k); } console.log(out.map(f => f()));
Show answer
It logs [3, 3, 3]. The variable k is declared once, outside the loop header, so there is only one binding. Every closure captures that same binding, which holds 3 after the loop ends. Moving the declaration into the header (for (let k = 0; k < 3; k++)) logs [0, 1, 2].
Exercise
Rewrite for (var i = 0; i < 3; i++) { setTimeout(() => console.log(i), 0); } so it logs 0, 1, 2 without using let or const.
Show answer
Wrap the body in an IIFE that receives i as a parameter: for (var i = 0; i < 3; i++) { (function (n) { setTimeout(function () { console.log(n); }, 0); })(i); }. Each call creates a new function scope with its own n.