Sub topic 12
let, const and Closures in Loops
This chapter assumes you know how let, const and var differ in scope, and that you can write arrow functions. It also assumes you understand that a closure is a function that remembers the variables around it.
One Binding or Many?
A binding is the link between a variable name and a storage slot. When you declare the loop variable of for...of or for...in with let or const, JavaScript creates a fresh binding for every iteration. A closure created inside the loop body captures the binding for its own iteration. It does not capture a single variable that keeps changing.
With var, the loop variable is function-scoped, so there is only one binding for the whole loop. Every closure points at that same slot, and by the time the closures run, the slot holds the last value.
const fns = [];
for (const x of [1, 2, 3]) {
fns.push(() => x);
}
console.log(fns.map(f => f())); // [1, 2, 3]
const fnsVar = [];
for (var y of [1, 2, 3]) {
fnsVar.push(() => y);
}
console.log(fnsVar.map(f => f())); // [3, 3, 3]for...in follows the same rule, because it binds a key string on each pass instead of a value.
Callbacks That Run Later
The bug usually shows up with asynchronous callbacks, which run after the loop has finished:
const tasks = ['save', 'sync', 'notify'];
for (const task of tasks) {
setTimeout(() => console.log('done:', task), 0);
}
// done: save
// done: sync
// done: notifyIf you change const to var, this code logs done: notify three times.
const Works Here but Not in a Classic for Loop
const is safe in for...of and for...in. Your code never reassigns the variable, because each iteration gets a new binding. A classic for loop is different: the update expression i++ reassigns the variable. In the classic loop, let gives you per-iteration copies, but const fails.
for (let i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 0); // 0, 1, 2
}
try {
for (const j = 0; j < 3; j++) {
console.log(j); // logs 0 once
}
} catch (err) {
console.log(err.name); // TypeError
}Common Errors
| Symptom | Cause | Fix |
|---|---|---|
| Every callback sees the last value | Loop variable declared with `var` | Declare it with `let` or `const` |
| `TypeError: Assignment to constant variable` | `const` in a classic `for` loop with `i++` | Use `let` |
| Loop variable is still readable after the loop | `var` leaks into the function scope | Use `let` or `const` to keep it block-scoped |
Exercise
What does this code log, and what one-word change makes it log ['a', 'b']? const fns = []; for (var k in { a: 1, b: 2 }) { fns.push(() => k); } console.log(fns.map(f => f()));
Show answer
It logs ['b', 'b'], because var creates one shared binding for k, and that binding holds 'b' when the closures run. Changing var to const (or let) gives each iteration its own binding, so the output becomes ['a', 'b'].
Exercise
Why does for (const item of list) work, while for (const i = 0; i < n; i++) throws?
Show answer
for...of creates a new const binding for each iteration and never reassigns it. The classic for loop's update expression i++ tries to reassign the same const binding, and that throws a TypeError.