$ ./guess_the_languageProblem Solving — fix the bug
Problem Solving — fix the bug · medium · #126

Which fix removes the bug?

for (var i = 0; i < 3; i++) {
  setTimeout(() => console.log(i), 0);
}
  1. Declare the counter with let i instead
  2. Declare the counter with var i instead
  3. Move the timeout call outside the loop
  4. Pass i as the third setTimeout argument
var is function-scoped so every callback sees the final 3; let binds a fresh i per iteration.
Play Problem Solving ▸