Should I assign the length of array to another variable in for loop?

3133 views javascript
3

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?

answered question

1 Answer

0

No benefit, 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.

posted this

Have an answer?

JD

Please login first before posting an answer.