This code works and each callback is referencing a different i it indicates that for each loop iteration a new copy of i is created, due to that the callback forms a closure with a distinct "i" each time
const arr = [10, 12, 15, 21];
for (let i = 0; i < arr.length; i++) {
setTimeout(function() {
console.log('Index: ' + i + ', element: '+ arr[i]);
}, 3000)
}
This gives error: Assignment to constant variable.
Why, in this case, isn't a new constant i is created for each loop iteration?
const arr = [10, 12, 15, 21];
for (const i = 0; i < arr.length; i++) {
setTimeout(function() {
console.log('Index: ' + i + ', element: '+ arr[i]);
}, 3000)
}