Can someone explain to me why the code does not act as expected?
WHy would this happen? I know it is due to "scoping", but I don't know the exact mechanism.
"Considering the above code, the console will display four identical messages "The value undefined is at index: 4". "
const arr = [10, 12, 15, 21];
for (var i = 0; i < arr.length; i++) {
setTimeout(function() {
console.log(`The value ${arr[i]} is at index: ${i}`);
}, (i+1) * 1000);
}
declare i using 'let' solves the problem;
putting setTimeOut() into IIFE also solves the problem, but I could not understand why.