/this code works and each callback is referencing to 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 not in this case 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)
}
++i doesn't modify the instance of i - it creates a new instance with an incremented value and assigns it back to i. If i is defined as a const, you cannot assign the value back to it, and hence the error.
Because a constant must not be changed, you can't i++ on a constant.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const