const arr = [1, 2, 3]
for (let i = 0; i < arr.length; i++) { // can't use const
  console.log(i, arr[i]);
}
for (const i in arr) { // const is ok
  console.log(i, arr[i]);
}
Why can "for in" use const but "for" can't?
You can't use const in the first loop because of i++ which will reassign the variable i.
In the for in loop, i can be a const because it is defined for each iteration.
in the const element in arr the element is the same as element in the const element = arr[i] in the classical forloop. It is a constant variable with local scope, so it is declared and destroyed in each iteration.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With