0

I have recently come up with a question asking to find outputs of these 2 code snippets:

First one:

let i;

for (i = 0; i <= 4; i++) {
  setTimeout(() => {
    console.log(i);
  }, 0);
}
Second one:

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

I am familiar with how Event Loop works. in Each iteration callback function inside setTimeout is getting added to the task queue after waiting for 0 millisecond. As soon as Call stack is empty those callback functions are fired.

But Both Code Snippets are giving different results.

Help me to get an explanation on why they are giving different results.

Samandar
  • 1
  • 1
  • Put simply, in the second snippet each for loop iteration has its own `i`. –  May 04 '21 at 07:31
  • In the first code snippet, each callback function of `setTimeout` forms a closure over the _same_ variable `i`, whereas in the second code snippet, each iteration of the loop has a _different_ `i` variable, this means that each time `setTimeout` is called, its callback function forms a closure over a _different_ `i` variable, which was created just for that iteration of the loop. if you are interested in understanding this problem of closures in loops, here's an [article](https://blog.yousafkhan.me/understanding-closures-in-loops-problem-and-how-it-is-solved-in-es6) about this problem. – Yousaf May 04 '21 at 07:40
  • Thank you @Yousaf for your explanation and your article is great. – Samandar May 07 '21 at 17:31

0 Answers0