Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 cannot fathom 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?

like image 891
Tomáš Zato - Reinstate Monica Avatar asked Oct 21 '19 09:10

Tomáš Zato - Reinstate Monica


People also ask

Is const better than let?

It's easier to understand if you use one identifier for the URL, a different one for the query string, and finally, an identifier to store the parameter value you were after. This is why I favor `const` over `let` in ES6. In JavaScript, `const` means that the identifier can't be reassigned.

Can I use const inside for loop?

When use const in for of loop, in each iteration you get a new variable, which is scoped only to that iteration. I use let only when i want to modify variable's value. In below example you can't use const because the value of variable is modified by increment one until the condition is false.

Can we use let in for loop?

According to MDN using let in the for loop like that should bind the variable in the scope of the loop's body.

Is it better to use a for of loop?

In general, you should use a for loop when you know how many times the loop should run. If you want the loop to break based on a condition other than the number of times it runs, you should use a while loop.


2 Answers

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 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}]`);
}
like image 87
T.J. Crowder Avatar answered Oct 20 '22 08:10

T.J. Crowder


There is a simple reason for the prevalence of for(let i instead of for(const i among even experienced devs/tutorial makers who are not modifying the value in the loop body and understand const/let.

Many people see const as a 'constant' which should never change. ever. (of course it never changes). But they further feel awkward 'redefining multiple constants with the same name'. For example, having const server = 'fun.example.com' in one place, and const server = 'boring.example.com' in another place would be 'objectionable'.

The variables in loops (at least in most C-like syntax languages which JavaScript is based on) are the variables that change THE MOST. Nothing gets it's value changed more than the 'i' in all the for loops. The 'i' typically ends up being a 'register variable' on the CPU itself (not in RAM) so that it can 'change faster'. And this was even true in JavaScript since it's inception with 'var', and is still true when you do a simple for(let i=0;i<50;i++). ie for(const i=0;i<50;i++) throws an error.

So you can start to see the dissonance between an 'i' that changes (or is redefined) potentially thousands of times per second as you iterate through a list and for(const i. So for(const i... 'looks' or 'feels' like i will only ever have the first value it is assigned. It seems 'wrong' to say const i.. and on the next line of code, i could be totally different values each time 'through the loop'. And even if you 'know' you are 'redefining it for each run through the loop', to some devs, that itself is questionable.

For this reason, many devs prefer to reserve const in JavaScript for 'values that are defined once and represent a single value throughout the 'whole execution of the program' or at least 'everything in a class'.

So the answer to the question in your 'title' (should I use) is probably 'keep using const since you have a reason and it makes sense to you'. And the answer to the doubt you had of "why is for(let i so common" is what I answered here as well. For some, they just have habit of for(let because it works for both 'for loops' and 'iterations through list'. For others, it's a conscious choice because they don't like 'redefining a const' over and over.

And I would humbly suggest that if you do use const please don't use i for the 'item' since i is so associated with an integer variable that increments. At least if you use a good name like item it feels more comfortable thinking of it as a single thing that only existed once. And I humbly suggest that if you use 'let' also don't use let i of for the same reason. Use i only for actual incrementing items. Ie use for(let item of items) or for(let i=0;i<y;i++)

like image 26
AwokeKnowing Avatar answered Oct 20 '22 07:10

AwokeKnowing