In closures we know for each loop iteration variable "i" is a fresh copy, then why const "i" not work in a loop

Viewed 31

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)
}
2 Answers

++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.

Related