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);
}
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.