0

Declaring i before the for loop gives output as 3 3 3.

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

//Output 3 3 3

Declaring i in the for loop gives output as 1 2 3:

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

//Output 1 2 3

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
krypton
  • 61
  • 2
  • 7

1 Answers1

1

When you use let i = 0;, the variable i has its scope restricted to the block scope of the for loop, e.g. between the two curly braces.

When you have let i; outside of the for loop, the variable i is restricted to the block scope enclosing the for loop, not the scope of the for loop itself, and you see this behavior occur.

Rubydesic
  • 3,386
  • 12
  • 27