Ask any question about JavaScript here... and get an instant response.
Post this Question & Answer:
Why does my closure not retain the value of a loop variable in a setTimeout callback?
Asked on Jan 09, 2026
Answer
Closures in JavaScript capture variables by reference, not by value. In a loop, this can lead to unexpected behavior when using functions like "setTimeout". Here's how you can correctly capture the loop variable using "let" or an IIFE.
<!-- BEGIN COPY / PASTE -->
for (let i = 0; i < 3; i++) {
setTimeout(() => {
console.log(i);
}, 1000);
}
<!-- END COPY / PASTE -->Additional Comment:
✅ Answered with JavaScript best practices.- Using "let" in the loop declaration creates a new block scope for each iteration, capturing the current value of "i".
- Alternatively, you can use an Immediately Invoked Function Expression (IIFE) to create a new scope for each iteration if "var" is used.
- This ensures that each "setTimeout" callback retains the correct value of "i" when it executes.
Recommended Links:
