1

when I use a basic for loop like this:

const digits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

for (let i = 0; i < digits.length; i++) {
  console.log(digits[i]);
}

I got error when I change the iterator to a const variable as the consts can't be changed so I have to declare it using var or let ... although, it's ok when I use The For...in loop:

const digits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

for (const index in digits) {
  console.log(digits[index]);
}

and the For...of loop:

const digits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

for (const digit of digits) {
  console.log(digit);
}

so .. could anyone help and tell me why this is happening and why const is available to use only with the "for of" and "for in" loops and not with the basic for loop. thank you.

Migo
  • 31
  • 4
  • Simple answer is that `i++` changes the value of the variable but you can't change value a `const` variable. It means *constant*. Using `for in` on arrays is not a good practice either – charlietfl Aug 16 '20 at 23:26
  • The for-of and for-in loops actually scope the `const` to the *inside* of the loop's statement. So it isn't mutating the `const` at all, but rather is discarding the old one and creating a new one in the new block scope on every iteration. The syntax doesn't make that very obvious, unfortunately. –  Aug 16 '20 at 23:43

0 Answers0