Why does a var loop with setTimeout print the same number, and how do you fix it?
Quick answer
`var` is shared across the loop, so all callbacks read the final value. Use `let` for a per-iteration binding.
In detail
With `var` there is one binding shared by every iteration; by the time the timers fire, the loop has finished and they all read the final value. `let` creates a fresh binding each iteration, capturing the value at that step. Before `let`, an IIFE was used to capture the value.
for (var i = 0; i < 3; i++) setTimeout(() => console.log(i));
// 3 3 3
for (let i = 0; i < 3; i++) setTimeout(() => console.log(i));
// 0 1 2Why interviewers ask this: The canonical closure + scope output question.
This is 1 of 118+ questions in the JavaScript Interview Kit
Get every question with detailed answers, follow-ups and real code — plus coding challenges and a last-minute revision sheet. One-time payment, instant access.
⚡ Get the JavaScript Interview Kit → ₹299