3

All examples of for...of that I have seen use let to define the iteration variable, for example here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of

Is it not a good style to say something like

for (const x of xs) {
    ...
}

if x is never changed inside the body of the loop?

akonsu
  • 28,824
  • 33
  • 119
  • 194
  • It does change though - `x` gets replaced on every iteration of the loop. It seems like a very strange choice to use a constant here. – Joe Clay Mar 14 '16 at 15:10
  • 1
    @Joe: every iteration "has its own" `x`. – Felix Kling Mar 14 '16 at 15:15
  • @FelixKling - Ah, okay, I wasn't 100% how that worked. Still, I think in terms of the semantics of it, using `const` for a value that isn't constant is a poor choice. – Joe Clay Mar 14 '16 at 15:16
  • 1
    Depends... do you want to _protect_ against inadvertently changing it within the loop? – James Thorpe Mar 14 '16 at 15:18
  • but then it is a bad practice to reassign, say, function arguments, I would think that the same could apply to loop variables. – akonsu Mar 14 '16 at 15:19
  • 1
    @Joe: I think this is more an issue of familiarity. So far, any variable you declared in the header was shared between all iterations, so we are used to thinking that there is only one binding with that name. But with block scope, that changes. We will need to change how we "perceive" loops. `let x` means that every iteration has its own `x`, and it can be changed in the loop body. `const x` means the same, except the binding cannot be changed. – Felix Kling Mar 14 '16 at 15:20
  • @FelixKling - So does `x` effectively go out of scope at the end of each iteration and then get redefined? – Joe Clay Mar 14 '16 at 15:22
  • 1
    @JoeClay [ES2015 13.7.5.13 (5)(g)](http://www.ecma-international.org/ecma-262/6.0/index.html#sec-for-in-and-for-of-statements) creates a new LexicalEnvironment for each loop iteration in steps `iii` through `v` – apsillers Mar 14 '16 at 15:29
  • Makes sense now I think about it! I'd always been under the impression the variable got defined once and then just reassigned on each iteration - guess I learned something new today! – Joe Clay Mar 14 '16 at 15:30
  • @JoeClay For `for(;;)` looks, not `for..in/of` with `let/const` – loganfsmyth Mar 14 '16 at 16:00
  • @JoeClay: Less technical: [Explanation of `let` and block scoping with for loops](http://stackoverflow.com/q/30899612/1048572) – Bergi Mar 14 '16 at 16:18

2 Answers2

3

Using const in a for of loop is totally fine. If you consider it good style to use const for all variables that you don't assign to, go for it. It's just that most people don't bother and go for let by default.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
0

Only use let when you can't use const.
Never user var.

I don't remember the source of this sentence but it works pretty well to me.

Cohars
  • 3,822
  • 1
  • 29
  • 50