I'm just trying to understand closures in Javascript. I came across below three examples.
Expample 1:
for (var i = 0; i <= 10; i++) {
setTimeout(function() {
console.log("i :" + i)
}, i * 1000);
}
And the output is as expected as it prints "i : 11" to the console 11 times because only one scope is created for entire loop that is global scope.To have different scope in each iteration I used IIFE(Immediately invoked function expression) please see the below code snippet.
example: 2
for (var i = 0; i <= 10; i++) {
(function(i) {
setTimeout(function() {
console.log("i : " + i)
}, i * 1000)
})(i);
}
It prints from "i:0" to "i:10" as expected because different scope is created for each iteration.
I'm not able to understand what exactly is happening in the below code snippet.
example :3
for (let i = 0; i <= 10; i++) {
setTimeout(function() {
console.log("i :" + i)
}, i * 1000);
}
It prints from "i:0" to "i:10".
1 .I'm not able to understand why the output is not as same as first example i.e print "1:11" 11 times?
2 . Is different scope is being created for each iteration if I use block scope?
3 . If different scope is being created, then how is it different from example-1?