I know the difference between let and var. let is block scope and var is functional scope.
for(var i=0; i< 3; i++){
setTimeout(function(){
console.log(i);
}, 10);
}
output : 3
3
3
I know how above code snippet is working(console.log(i)
is executing at that time when value of i is 3, because scope of i is global).
But
for(let i=0; i< 3; i++){
setTimeout(function(){
console.log(i);
}, 10);
}
output : 1
2
3
the above code snippet confusing me. according to me it should throw Reference Error(because the time when console.log(i)
execute, will look the value of i in global scope not in local scope, and i is not declare/defined in global. so it should give reference error.)
Anyone who can explain how 2nd for loop working on Runtime ?