What is logged?
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 0);
}Options
- 0 1 2
- 3 3 3 (Correct option)
- undefined x3
- 2 2 2
Answer
3 3 3
Why
setTimeout callbacks run later, after the loop has finished.
var creates ONE variable i for the whole function, shared by all three callbacks. When they run, i is already 3.
With let i, each loop iteration gets its own new i, so it logs 0 1 2.
Remember
Loops with callbacks: use let, not var.