JavaScript·Intermediate·Output based·1 min read
Why do closures in a loop sometimes produce the same result?
Short interview answer
A loop declared with var has one function-scoped binding, so every callback closes over that same binding and observes its final value. let creates a fresh per-iteration binding. A factory or IIFE also works by creating a new lexical environment for each callback.
Example
for (var i = 0; i < 3; i++) { setTimeout(() => console.log(i)); // 3, 3, 3 — one shared `i`}
for (let j = 0; j < 3; j++) { setTimeout(() => console.log(j)); // 0, 1, 2 — fresh `j` per iteration}Key takeaway
Explain the underlying mental model clearly, then support it with a concrete example and its trade-offs.