0

The following piece of code will produce 1, 2, 3, 4

const array = [1, 2, 3, 4];

for (let i = 0; i < array.length; i++) {
  setTimeout(() => {
    console.log(array[i]);
  }, 1000);
}

Whereas using var i = 0 in the for loop will produce undefined, undefined, undefined, undefined

const array = [1, 2, 3, 4];

for (var i = 0; i < array.length; i++) {
  setTimeout(() => {
    console.log(array[i]);
  }, 1000);
}

I understand var and let have different scopes but can somebody explain why in the var example, i evaluates to 4 in each iteration?

M11CH
  • 46
  • 7
  • 2
    Because the loop has finished and `i` has been incremented to 4, before the first `setTimeout()` callback has been invoked. – Ivar Jan 16 '23 at 15:00
  • Because by the time the function specified in your `setTimeout ` runs, the loop has finished and `i = 4`. – mykaf Jan 16 '23 at 15:00

0 Answers0