for...of loop. Should I use const or let?

Tomáš Zato - Reinstate Monica picture Tomáš Zato - Reinstate Monica · Oct 21, 2019 · Viewed 11.5k times · Source

When using a for of loop, both of these are allowed and work:

const numbers = [1,2,3];
// works
for(let number of numbers) {
    console.log(number);
}
// also works
for(const number of numbers) {
    console.log(number);
}

I always use const since I annot fanthom changing the number variable in any context, but when I see a for...of loop in other people's code, it often uses let. Maybe there's a drawback to const that I didn't see? Browser bugs?

Why use const and when to use let in for...of loops?

Answer

T.J. Crowder picture T.J. Crowder · Oct 21, 2019

Why use const and when to use let in for...of loops?

If there are no assignments to the identifier within the loop body, it's basically a matter of style whether you use let or const.

Use const if you want the identifier within the loop body to be read-only (so that, for instance, if someone modifies the code later to add an assignment, it's a proactive error). Use let if you want to be able to assign to it (because you have an assignment in your code, or you want someone to be able to add one later without changing the declaration).

You can do this with for-of and for-in loops. A for loop's control variable is normally not constant (since in the normal case you update it in the "update" clause of the for; if you don't, for may be the wrong loop to use), so you normally use let with it.


For clarity, here's an example with an assignment within the loop body:

for (let str of ["a", " b", " c "]) {
    str = str.trim();
//  ^^^^^----- assignment to the identifier
    console.log(`[${str}]`);
}

If you use const for str in the above, you get an error:

for (const str of ["a", " b", " c "]) {
    str = str.trim();
//  ^^^^^----- Error
    console.log(`[${str}]`);
}