5

I am trying to understand the reason but didn't found it yet. So asking here.

The below prints i value fine when I use let i = 0

for(let i=0; i < 5; i++){
  setTimeout(() => {
    console.log(i) // 0 1 2 3 4
  }, 1000)
}

The below prints i value 5 when I use var i = 0

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

Please help me to understand why it works this way?.

Soham
  • 705
  • 3
  • 19
  • I did take a look https://wesbos.com/for-of-es6 but it just says let is block-scoped. – Soham May 23 '20 at 06:09
  • this is literally why they introduced the `let` keyword in javascript. Just look at its description – Adassko May 23 '20 at 06:10
  • 1
    Also relevant: [Javascript infamous Loop issue?](https://stackoverflow.com/questions/1451009/javascript-infamous-loop-issue) – VLAZ May 23 '20 at 06:13
  • This is not a duplicate question. I am asking **why** and all other questions are **how to**? – Soham May 23 '20 at 06:14
  • 1
    They also explain the reason - `var` is scoped to the whole function, so you get one variable for every loop iteration. When the loop finishes, and the delayed functions execute, they all read the same value. `let` is scoped only to the block there is a separate value for each iteration. – VLAZ May 23 '20 at 06:16
  • Have a look at [this answer](https://stackoverflow.com/a/29558498/) which directly addresses this. – VLAZ May 23 '20 at 06:18

0 Answers0