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 have met for...of and for...in in earlier chapters. The question here is narrow but causes real bugs: when a function created inside a loop refers to the loop variable, which value does it see later?
The Problem: Functions Outlive the Iteration
A closure is a function that keeps access to the variables in scope where it was created, even after that scope has finished running. Loops create closures all the time: callbacks pushed into an array, event handlers attached to elements, and setTimeout calls scheduled for later.
A closure does not capture a variable's value. It captures the binding, meaning the storage slot the name refers to. If several closures share one binding, they all see whatever that binding holds when they finally run. If each closure has its own binding, each one sees its own value.
The declaration keyword in the loop head decides which of these happens.
Fresh Bindings with let and const
When you declare the loop variable with let or const in a for...of or for...in head, JavaScript creates a new binding for every iteration. Each closure created during that iteration captures that iteration's binding.
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]With const x, the loop makes three separate bindings that hold 1, 2 and 3. With var y, there is one function-scoped binding. Each iteration assigns a new value to it, and after the loop it holds 3, so all three closures return 3.
for...in follows the same rules:
const user = { name: 'Ada', role: 'admin' };
const readers = [];
for (const key in user) {
readers.push(() => `${key}=${user[key]}`);
}
console.log(readers.map(r => r()));
// ['name=Ada', 'role=admin']Why const Works in for...of but Not in a Classic for
const in a for...of or for...in head is legal and is usually the best choice. Each iteration gets a brand-new binding that is initialized once and never reassigned, which is exactly what const allows.
A classic for loop is different, because its update expression reassigns the variable:
try {
for (const i = 0; i < 3; i++) {
console.log(i);
}
} catch (err) {
console.log(err.name); // TypeError
}
// 0
// TypeErrorThe body runs once and logs 0. Then i++ tries to reassign a constant and throws TypeError: Assignment to constant variable. In a classic for loop, use let.
The Classic for Loop Also Copies let Bindings
A classic for loop with let also gives each iteration its own binding. At the end of each iteration, the engine creates a new binding, copies the current value into it, and then runs the update expression on the new copy. Closures from earlier iterations keep their old bindings.
for (let i = 0; i < 3; i++) {
setTimeout(() => console.log('let', i), 0);
}
// let 0
// let 1
// let 2
for (var j = 0; j < 3; j++) {
setTimeout(() => console.log('var', j), 0);
}
// var 3
// var 3
// var 3The var version prints 3, not 2, because the loop stops only after j++ makes the condition j < 3 false. All the timers fire after the loop has finished, so they read the final value.
The Old Workaround and Why You No Longer Need It
Before ES2015 added let, developers worked around the shared var binding with an immediately invoked function expression (IIFE). The IIFE takes the current value as a parameter, which creates a new scope for each iteration:
var handlers = [];
for (var k = 0; k < 3; k++) {
(function (captured) {
handlers.push(function () { return captured; });
})(k);
}
console.log(handlers.map(function (h) { return h(); })); // [0, 1, 2]You will still find this pattern in older code. In new code, let or const does the same job with no extra function.
Common Errors and Edge Cases
Reusing an Outer Variable
The per-iteration binding only exists when you declare the variable in the loop head. If the head assigns to a variable that already exists, every iteration writes to that one outer binding:
let item;
const getters = [];
for (item of ['a', 'b', 'c']) {
getters.push(() => item);
}
console.log(getters.map(g => g())); // ['c', 'c', 'c']This acts like the var case even though item was declared with let. Declare the variable inside the loop head instead: for (const item of ...).
Leaking var After the Loop
A var loop variable stays in scope after the loop ends, which can hide bugs:
for (var n of [1, 2, 3]) {}
console.log(n); // 3
for (const m of [1, 2, 3]) {}
console.log(typeof m); // 'undefined' (m is not in scope here)Capturing a Binding Is Not Copying an Object
A fresh binding per iteration protects you from reassignment, not from mutation. If the value is an object and something changes that object later, the closure sees the change:
const rows = [{ count: 1 }, { count: 2 }];
const readCounts = [];
for (const row of rows) {
readCounts.push(() => row.count);
}
rows[0].count = 100;
console.log(readCounts.map(r => r())); // [100, 2]If you need a snapshot, copy the primitive you care about (const count = row.count;) or clone the object inside the loop body.
Destructured Bindings Are Fresh Too
Each name you destructure in the loop head gets its own per-iteration binding:
const prices = new Map([['apple', 1.2], ['pear', 0.8]]);
const labels = [];
for (const [fruit, price] of prices) {
labels.push(() => `${fruit}: ${price}`);
}
console.log(labels.map(l => l())); // ['apple: 1.2', 'pear: 0.8']Reassigning a let Loop Variable Does Not Change the Collection
With let, you can reassign the loop variable, but that only changes the local binding. It does not write back into the array:
const nums = [1, 2, 3];
for (let v of nums) {
v *= 10;
}
console.log(nums); // [1, 2, 3]To transform the elements, build a new array with map, or write to nums[i] using an index.
Summary Table
| Loop head | Binding per iteration | Closures see | Reassign in body |
|---|---|---|---|
| `for (const x of ...)` / `for (const k in ...)` | New | Their own value | No |
| `for (let x of ...)` / `for (let k in ...)` | New | Their own value | Yes, local only |
| `for (var x of ...)` / `for (var k in ...)` | Shared, function-scoped | The final value | Yes |
| `for (x of ...)` with outer `x` | Shared outer binding | The final value | Yes |
| `for (let i = 0; ...; i++)` | New, copied forward | Their own value | Yes |
| `for (const i = 0; ...; i++)` | Not applicable | Not applicable | Throws `TypeError` on `i++` |
Exercise
What does this code log, and why? const out = []; for (var i in ['a', 'b']) { out.push(() => i); } console.log(out.map(f => f()));
Show answer
It logs ['1', '1']. With var there is one shared binding, and for...in assigns it the string keys '0' and then '1'. Both closures read the binding after the loop ends, when it holds '1'. Note that the values are strings, because for...in yields string keys.
Exercise
Fix this code so each timer logs its own word, without changing the array: let word; for (word of ['red', 'green']) { setTimeout(() => console.log(word), 0); }
Show answer
Declare the variable in the loop head so each iteration gets its own binding: for (const word of ['red', 'green']) { setTimeout(() => console.log(word), 0); }. It then logs red and then green. The original logs green twice because every iteration assigns to the single outer binding.
Exercise
Why does for (const i = 0; i < 3; i++) throw while for (const i of [0, 1, 2]) works?
Show answer
In for...of, each iteration creates a new const binding and initializes it once, so nothing is ever reassigned. In the classic for loop, the update expression i++ reassigns the existing binding, which const forbids. That raises a TypeError after the first iteration.