1

Typically I'd use a let i in the following first two cases:

> for (const i in ["red", "green", "blue"]) { console.log(i) }
0
1
2

> for (const i of ["red", "green", "blue"]) { console.log(i) }
red
green
blue

> for (const i = 0; i < 10; i++) { console.log(i) }
0
TypeError: Assignment to constant variable.

But the Mozilla documentation stated a const can be used. So the i ceased to exist after the end of the block { console.log(i) }? Isn't that not true if it is the third case above?

Is it a subtle rule? The loop variable for for ( in ) and for ( of ) loop ceases to exist after the block, but for the for (;;) loop, it stays? It is somewhat subtle -- is it in any of the ES6 specs?

nonopolarity
  • 146,324
  • 131
  • 460
  • 740
  • @Yaka: There is no "declaring i again and again". The constant is declared in the initialisation step, which only occurs once. – Amadan Dec 19 '19 at 08:59

2 Answers2

2

The variable in each case does cease to exist after the loop. You can see it work as you expect if you use let instead of const.

for (let i in ["red", "green", "blue"]) { console.log(i) }
for (let i of ["red", "green", "blue"]) { console.log(i) }
for (let i = 0; i < 10; i++) { console.log(i) }
console.log(i); // error, because `i` is local

However, you cannot use ++ on a constant, which accounts for your error. The constant or variable in for..of and for..in constructs is recreated in each loop; but you can't do that with for.

However, if you don't try to modify the constant, it again works as expected:

for (const i = [0]; i[0] < 10; i[0]++) { console.log(i[0]) }
console.log(i) // error, because `i` is local
Amadan
  • 191,408
  • 23
  • 240
  • 301
  • I don't mean after the whole loop -- I mean after **each iteration** of `{ console.log(i) }`, the `i` ceases to exist, but for the `for (;;)` loop, the `i` doesn't cease to exist, so it is kind of subtle – nonopolarity Dec 19 '19 at 09:08
  • Yes, I had a bit of a mind blowage on `for (const i in/of ...)`, where `i` is clearly local, and clearly changes, and yet clearly constant. But it is important to note that `for(;;)` is a very different construct from `for (let/const ... in/of ...)`, even if they share the keyword. – Amadan Dec 19 '19 at 09:18
-2

If you need to limit the scope of the loop variable justo surround the loop with another block and use let.

{
    for (let i in ["red", "green", "blue"]) {console.log(i);}
}
console.log(i);

This way the last console.log will throw Reference error, because it's not defined in its scope

Sailendra
  • 1,318
  • 14
  • 29