Sub topic 12
let vs var in Loops: Scope and Closures
This chapter assumes you already know how the classic for loop runs (initializer, condition, update, body). It also assumes you can write arrow functions and know that a function can use variables from the scope around it. That last idea has a name. A closure is a function together with the variables it captured from where it was created.
Most of the time, let and var in a loop behave the same way. The difference shows up when the loop body creates a function that runs later, such as a callback, an event handler, or a timer. Then one keyword gives you the values you expected and the other gives you the final value every time.
The Working Model: Bindings, Not Values
A closure does not copy the value of a variable. It keeps a reference to the binding, which is the storage slot that the variable name refers to. When the closure runs later, it reads whatever that slot holds at that moment.
So the useful question is not "what was i when the function was created?" Ask instead: "Which binding does this function point to, and what does that binding hold when the function runs?"
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]With var, there is one binding i for the whole enclosing function (or the whole script). All three arrow functions point at it. By the time they run, the loop has pushed i to 3, so all three return 3.
With let, the loop creates a new binding j for each iteration. Each arrow function captures a different slot, and each slot keeps the value it had when its iteration ended.
Why var Behaves This Way: Function Scope and Hoisting
var is function-scoped. A var declaration belongs to the nearest enclosing function, or to the global scope if there is no function. Blocks such as { ... }, if bodies, and loop bodies do not limit it. The declaration is also hoisted, meaning it is registered at the top of the function before any code runs and starts out as undefined.
function demo() {
console.log(k); // undefined (hoisted, not yet assigned)
for (var k = 0; k < 2; k++) {}
console.log(k); // 2 (still visible after the loop)
}
demo();let and const are block-scoped. They exist only inside the nearest { ... } block, or inside the loop header and body for a for loop. Before the declaration line runs, the name sits in the temporal dead zone (TDZ). Accessing it there throws a ReferenceError instead of quietly giving undefined.
function demo2() {
for (let k = 0; k < 2; k++) {}
try {
console.log(k);
} catch (e) {
console.log(e.name); // "ReferenceError"
}
}
demo2();| Property | `var` | `let` | `const` |
|---|---|---|---|
| Scope | Function (or global) | Block | Block |
| Visible after the loop | Yes | No | No |
| Access before declaration | `undefined` | `ReferenceError` (TDZ) | `ReferenceError` (TDZ) |
| New binding per `for` iteration | No | Yes | Yes, but the update step can't reassign it |
| Creates a property on `globalThis` at top level of a script | Yes | No | No |
How the Per-Iteration Binding Works Internally
The language specification gives for (let ...) loops special treatment. In simplified form, the steps are:
- Create a loop scope and run the initializer (
let i = 0) in it. - Before the first iteration, create a fresh scope and copy the current value of
iinto a new binding. - Test the condition, then run the body using that iteration's binding.
- At the end of the iteration, create another fresh scope and copy the current value of
iinto it. - Run the update expression (
i++) on the new binding, then go back to step 3.
Step 5 explains why closures from earlier iterations are not affected by later increments. The increment always happens on a copy that belongs to the next iteration.
Edge case: changing the variable inside the body
The copy carries over whatever value the binding holds at the end of the iteration. If the body changes the loop variable, both the closure from that iteration and the next iteration see the change.
const fns = [];
for (let i = 0; i < 3; i++) {
fns.push(() => i);
i++; // changes this iteration's binding
}
console.log(fns.map((f) => f())); // [1, 3]In the first iteration, the binding starts at 0, the closure is pushed, and the body changes it to 1. The next iteration copies 1, the update makes it 2, the condition passes, and the body raises it to 3. The third copy becomes 4 and fails the condition. That leaves two closures, which return 1 and 3.
Edge case: closures in the initializer
A function created inside the initializer captures the loop scope from step 1, not any iteration's copy. It never sees the increments.
for (let i = 0, first = () => i; i < 3; i++) {
if (i === 2) console.log(first()); // 0
}You will rarely write this on purpose. It is still a useful check on whether you have the model right.
The Classic Bug: Callbacks Scheduled in a Loop
The var problem matters most with asynchronous callbacks, because they always run after the loop has finished.
for (var a = 0; a < 3; a++) {
setTimeout(() => console.log("var:", a), 0);
}
// var: 3 (three times)
for (let b = 0; b < 3; b++) {
setTimeout(() => console.log("let:", b), 0);
}
// let: 0, let: 1, let: 2The same thing happens with event listeners attached in a loop. Every button ends up reporting the last index.
Fixes from before let existed
Older code solved this by creating a new function scope for each iteration, usually with an IIFE (immediately invoked function expression), or by passing the value as an argument:
for (var c = 0; c < 3; c++) {
((captured) => {
setTimeout(() => console.log("iife:", captured), 0);
})(c);
}
// iife: 0, iife: 1, iife: 2
for (var d = 0; d < 3; d++) {
setTimeout((value) => console.log("arg:", value), 0, d);
}
// arg: 0, arg: 1, arg: 2Both versions work because captured and value are function parameters. Each call creates a new binding for them. In modern code, use let and skip these workarounds. You should still recognize them when you read older code.
const in Loops
const also gets a fresh binding per iteration, but the classic for loop's update step tries to reassign it:
try {
for (const i = 0; i < 3; i++) {}
} catch (e) {
console.log(e.name); // "TypeError" (assignment to constant variable)
}The initializer and the first condition check succeed. The error appears at the first i++. In for...of and for...in, nothing ever reassigns the variable, because the loop creates a brand-new binding for each element. const is therefore the usual choice there:
const callbacks = [];
for (const name of ["ada", "grace"]) {
callbacks.push(() => name.toUpperCase());
}
console.log(callbacks.map((f) => f())); // ["ADA", "GRACE"]while Loops Have No Per-Iteration Header Binding
Only the for family gets the automatic copy. A while loop's counter is declared outside the loop, so every closure shares it, even if you declared it with let:
const shared = [];
let n = 0;
while (n < 3) {
shared.push(() => n);
n++;
}
console.log(shared.map((f) => f())); // [3, 3, 3]
const fresh = [];
let m = 0;
while (m < 3) {
const current = m; // new binding each time the block runs
fresh.push(() => current);
m++;
}
console.log(fresh.map((f) => f())); // [0, 1, 2]The fix works because a block-scoped declaration inside the body gets a new binding every time the block runs. This holds for any loop type.
Common Errors and Decision Rules
| Symptom | Likely cause | Fix |
|---|---|---|
| Every callback logs the final index | `var` counter shared by all closures | Use `let` in the `for` header |
| Callbacks from a `while` loop all see the last value | Counter declared outside the loop | Copy it into a `const` inside the body |
| `TypeError` on the first update | `const` in a classic `for` header | Use `let`, or switch to `for...of` |
| `ReferenceError` after converting to `let` | Code after the loop read the counter | Declare a variable outside the loop and assign it on purpose |
| Unexpected global property in a browser script | Top-level `var` | Use `let`/`const`, or ES modules |
The rules in short:
- Use
constinfor...ofandfor...inunless the body needs to reassign the variable. - Use
letfor counters in classicforloops. - Don't use
varin new code. Keep its function-scope behavior in mind when you read legacy code. - If a closure needs a snapshot of a value, put that value in a block-scoped binding created inside the iteration.
Exercise
What does this code log, and why? const out = []; for (var i = 0; i < 3; i++) { let copy = i; out.push(() => copy + i); } console.log(out.map((f) => f()));
Show answer
It logs [3, 4, 5]. Each closure gets its own copy binding (0, 1, 2), because let inside the body creates a new binding each iteration. All three share the single var i binding, which is 3 by the time the functions run. So the results are 0+3, 1+3, and 2+3.
Exercise
A teammate writes for (const i = 0; i < items.length; i++) { ... } and says it "crashes partway through." The array has five items. When exactly does the error happen, and what are two correct rewrites?
Show answer
The body runs once with i = 0. Then the update i++ tries to reassign a constant and throws a TypeError, so the crash happens right after the first iteration, not partway through the array. One rewrite changes const to let in the classic for loop. The other uses for (const item of items) if the index isn't needed, or for (const [i, item] of items.entries()) if it is.
Exercise
What does this log? const fs = []; for (let i = 0; i < 4; i++) { fs.push(() => i); i += 1; } console.log(fs.map((f) => f()));
Show answer
It logs [1, 3]. Iteration 1 starts with i = 0, pushes a closure, and the body sets that binding to 1. The next iteration copies 1, the update makes it 2, and the body sets it to 3. The next copy becomes 4, which fails the condition 4 < 4, so the loop ends. The two closures read their own bindings: 1 and 3.