Sub topic 12
let vs var in Loops: Scope and Closures
This chapter assumes you know how the classic for loop works and that you can write arrow functions. You should also know what a closure is: a function that keeps access to variables from the scope where it was created. The question here is which variable a closure sees when it is created inside a loop. The answer depends on whether the loop variable is declared with var or let.
Two Kinds of Scope
var is function-scoped. However many times the loop runs, a var declaration in a loop header creates one variable, and that variable belongs to the whole enclosing function (or to the global scope). Every iteration reads and writes that same variable.
let is block-scoped. In a for loop, the language goes further and creates a fresh binding of the loop variable for each iteration. It copies the current value into the new binding before running the increment step.
A closure captures a binding, meaning the variable itself, not a snapshot of its value. With var, every closure points to the one shared variable. With let, each closure points to its own variable.
Seeing the Difference
const withVar = [];
for (var i = 0; i < 3; i++) {
withVar.push(() => i);
}
console.log(withVar.map((f) => f())); // [3, 3, 3]
const withLet = [];
for (let j = 0; j < 3; j++) {
withLet.push(() => j);
}
console.log(withLet.map((f) => f())); // [0, 1, 2]The functions in withVar don't run until after the loop has finished. By then the shared i has been incremented to 3, which is the value that made the condition i < 3 false. All three functions read that final value. The functions in withLet each read a different j, and each j was frozen at its own iteration's value.
Where This Bites in Real Code
The usual trigger is a callback that runs later, such as a timer, an event handler, or a promise callback:
for (var k = 0; k < 3; k++) {
setTimeout(() => console.log("var:", k), 0); // var: 3, three times
}
for (let m = 0; m < 3; m++) {
setTimeout(() => console.log("let:", m), 0); // let: 0, 1, 2
}The var loop has a second side effect: k stays visible after the loop ends. Running console.log(k) below the loop prints 3. The let variable m doesn't exist outside its loop.
In older code written before let existed, you will see this bug fixed with an immediately invoked function expression (IIFE). The IIFE creates a new function scope on every pass:
const fns = [];
for (var n = 0; n < 3; n++) {
((captured) => {
fns.push(() => captured);
})(n);
}
console.log(fns.map((f) => f())); // [0, 1, 2]Today you get the same result by writing let in the loop header.
What About const?
const also creates a fresh binding per iteration. The catch is that the classic for loop reassigns its variable in the increment step.
| Loop header | Works? | Why |
|---|---|---|
| `for (let i = 0; i < 3; i++)` | Yes | A new binding is made each iteration, and reassignment is allowed |
| `for (const i = 0; i < 3; i++)` | No | The body runs once, then `i++` throws a `TypeError` |
| `for (const x of arr)` | Yes | Each iteration gets a new binding, and nothing is reassigned |
| `for (var i = 0; i < 3; i++)` | Yes, but | One shared binding that leaks outside the loop |
Exercise
What does this code print, and what single-word change makes it print 0, 1, 2? const out = []; for (var x = 0; x < 3; x++) { out.push(() => x * 10); } console.log(out.map((f) => f()));
Show answer
It prints [30, 30, 30]. All three closures share the one function-scoped x, which is 3 when they finally run. Changing var to let gives each iteration its own x, so the output becomes [0, 10, 20]. That is 0, 1, 2 multiplied by 10.
Exercise
Why does for (const i = 0; i < 3; i++) fail when for (const item of items) works?
Show answer
The classic for loop has to reassign i in its i++ step, and you can't reassign a const binding, so the loop throws a TypeError after the first pass. for...of never reassigns its variable. It creates a new const binding for each value.