1

code1:

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

output: 5,5,5,5,5

code2:

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

output: 0,1,2,3,4

Can anyone help me to understand why the output of code1 is: 5,5,5,5,5 and code2's output is: 0,1,2,3,4

Cerbrus
  • 70,800
  • 18
  • 132
  • 147
  • `setTimeout` is not blocking, the function passed as the first argument is executed after the loop (and any other code within the script/function containing the loop), and at that time `var` declared variable has been increased to 5. `let` declared variable is scoped inside the loop only, and every iteration round keeps the value of the variable. – Teemu Aug 21 '19 at 13:47
  • 2
    You'll need to wrap your mind around [closures](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures), but the simplest way to think about it is that your `let` variable creates a new "[cubby hole](https://security.stackexchange.com/a/53912/68692)" in memory for each loop, so each call to `setTimeout` get's it's own value, but `var` shares a "cubby hole", so all of the `setTimeout` callbacks have to share a single value. By the time they get called, their shared value has been updated to the value 5. – JDB Aug 21 '19 at 13:51

0 Answers0