3, 3, 3. var is function-scoped, so all callbacks share one i. By the time the callbacks run (after the loop, via the event loop), i is 3. All three callbacks log 3.
setTimeout and Closures in JavaScript Explained
What is the output of for (var i = 0; i < 3; i++) setTimeout(() => console.log(i), 0)?
The answer
More FAQs in setTimeout and Closures in JavaScript Explained
Use let instead of var (each iteration gets a fresh binding). Or use an IIFE to capture the current value of i as a parameter. Or pass i as an extra argument to setTimeout.
Because let is block-scoped and creates a fresh binding per iteration. Each callback closes over its own copy of i, which holds the value for that iteration. With var, all callbacks share one i.
No. The callback goes to the macrotask queue. The event loop runs it only after the current call stack is empty and all microtasks are done. So it runs after the synchronous loop finishes.
Still have questions?
Browse all our FAQs or reach out to our support team
Want to upskill yourself?
Your learning library
Small steps. Big possibilities.
Find your next course. Build something great.