0

I'm aware of the difference between the var & let variable declaration. I just executed the same piece of code using for loop & while loop. To my surprisingly I got the different output & I'm not able to differentiate the execution behavior difference between them.

I have attached 2 code snippets using While loop & For loop.

If anyone is aware of this then please help me.

let i = 0;
while(i < 5) {
  setTimeout(function() {
    console.log(i)
  }, 1000);
  i++;
}

for(let j = 0; j < 5; j++) {
  setTimeout(function() {
    console.log(j)
  }, 1000);
}

Thanks!

narwanimonish
  • 1,552
  • 17
  • 13
  • See https://stackoverflow.com/a/58044285 - declare a block-scoped variable inside the loop with `while` so it can be accessed inside the timeout – CertainPerformance Apr 05 '20 at 07:23
  • @CertainPerformance That's a good turnaround, but I was more interested in getting know why is this kind of change in behavior. Thanks for quick response. – narwanimonish Apr 05 '20 at 07:29
  • Because in the `while` loop, there's only one binding of `i`, which has reached 5 after the loop ends. In the `for` loop, there are 5 separate bindings of `j`, one for each iteration block. – CertainPerformance Apr 05 '20 at 07:55

0 Answers0