Reputation: 345
I'm learning Javascript and the for loop here looks exactly the same as in C. What I'm wondering is whether I should assign the length of a string to another variable in the loop. I usually do that in C when looping over a char array so the loop does not have to call strlen
with each iteration:
for (int i = 0, n = strlen(word); i < n; i++)
{
// code block
}
What I see from following tutorials is that a for loop in Javascript is just written without assigning array length of a variable:
for (let i = 0; i < arr.length; i++) {
// code block
}
Is there any advantage to assigning the length of the array to a variable in Javascript?
Upvotes: 3
Views: 560
Reputation: 5770
No benefit, not as important as in C because arr.length
is a static property i.e. it is not computed, unlike strlen
which would compute the length each time it is called.
edit: see for yourself, its a controversial issue but it seems like accessing the property directly is fastest
Upvotes: 8