2

Consider these 2 snippets:

With let:

for(let i = 0; i < 10; i++) {
    setTimeout(function() {
  console.log(i);
 }, 100)
}

With var:

for(var i = 0; i < 10; i++) { //HERE
    setTimeout(function() {
  console.log(i);
 }, 100)
}

From my understanding, let only affects the scoping of the variables, so why are the outputs of the 2 loops should be same, so why does let print 0-9 and var prints 10 10 times?

Ayush Gupta
  • 8,716
  • 8
  • 59
  • 92

1 Answers1

2

Because you have a timeout in your loop, none of your logs are being called until the entire loop is finished.

After the loop is finished, the value of i is 10 if you use var.

But let is block scoped, meaning it's the same value anywhere in the loop, even in an async function like setTimeout (unless you manually change it inside the loop) - because the loop creates a new scope on each iteration, it's almost like each iteration creates a new "instance" of the i variable when you use let, whereas using var each loop is using the same instance of the i variable.

I wrestled a bear once.
  • 22,983
  • 19
  • 69
  • 116