I'd like to understand the following code:
for (var i=0; i<3; i++){
setTimeout(() => {
console.log(i);
}, 1000);
}
console.log('After the Loop');
Prints After the loop,3,3,3
for (let i=0; i<3; i++){
setTimeout(() => {
console.log(i);
}, 1000);
}
console.log('After the Loop');
Prints After the loop,0,1,2
I know that the events are executed after the main, so the numbers of i appear after After the loop. And letmeans block scope (so iis visible in for-loop only) and varfunction scope (so it should be visible globally here), but I still don't see why the first prints 3,3,3.
Can anyone please provide a resonable explaination?
Thanks!