Number 1 doesn’t work properly but 2 and 3 works how?
-
const array = [1,2,3,4];
for(var i=0; i < array.length; i++) {
setTimeout(function(){
console.log('I am at index ’ + array[i])
}, 3000)
}
-
const array = [1,2,3,4];
for(let i=0; i < array.length; i++) {
setTimeout(function(){
console.log('I am at index ’ + array[i])
}, 3000)
}
-
const array = [1,2,3,4];
for(var i=0; i < array.length; i++) {
(function(closureI) {
setTimeout(function(){
console.log('I am at index ’ + array[closureI])
}, 3000)
})(i)
}
With the delay, for 1) you are executing the console log when i=4
, which produces an undefined value.
For 2) each instance of i
is distinct and thus so are the print statements.
For 3) closures provide a way for the function call to ‘remember’ the state of i
at that point in the loop iterations.
Why i is distinct in 2 just because of it is blocked scope?
Is function can create closure from both another function scope surrounding it and a block scope surrounding it ?
In 2 i
is distinct because of let
.
and let create blocked scope identifiers is that right?