JavaScript Loop Closures with let and var
Quick answer
Closures created in a loop can share one binding or capture separate iteration bindings, depending on the declaration form.
How it works
In a conventional for (let i = ...; ...; ...) loop, each iteration has its own binding for i. A var declared in the loop belongs to the surrounding function or script scope. Calling the saved functions after the loop exposes the difference. An outer let declared before the loop is also shared.
const tasks = []; for (let i = 0; i < 3; i++) tasks.push(() => i);console.log(tasks.map(f => f()).join(","));Expected output in Node.js:
0,1,2Each closure retains the iteration binding.
const tasks = []; for (var i = 0; i < 3; i++) tasks.push(() => i);console.log(tasks.map(f => f()).join(","));Expected output in Node.js:
3,3,3The functions read the shared binding after termination.
Common mistakes
Replacing var with let outside the loop header does not automatically create iteration bindings.
Practice
Change the let loop to use an outer let and trace its output.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
JavaScript Loop Closures with let and var — Knowledge Check
Apply the taught concept and predict the output.
Which loop form creates distinct iteration bindings for i?
Why do delayed var callbacks read 3?
What is needed to observe the capture difference?
What is the exact console output in JavaScript Loop Closures with let and var example 1?
const tasks = []; for (let i = 0; i < 3; i++) tasks.push(() => i);console.log(tasks.map(f => f()).join(","));What is the exact console output in JavaScript Loop Closures with let and var example 2?
const tasks = []; for (var i = 0; i < 3; i++) tasks.push(() => i);console.log(tasks.map(f => f()).join(","));