Why use
const
and when to uselet
infor...of
loops?
If there are no assignments to the identifier within the loop body, it’s 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}]`);
}