Repaso
EspaƱol
Frontend & WebIntermediateFE-03

What is logged?

for (var i = 0; i < 3; i++) {
  setTimeout(() => console.log(i), 0);
}

Options

  1. 0 1 2
  2. 3 3 3 (Correct option)
  3. undefined x3
  4. 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.

Key terms

Practice this question in Repaso