0

I have seen the following style of writing a for loop in JavaScript a number of times:

for(var i=0, n=myArray.length; i<n; i++) {
// do something
}

what is the advantage of that over the following?

for(var i=0; i<myArray.length; i++) {
// do something
}
5

1 Answer 1

3

In theory, it only has to look up the length of myArray once, instead of each time it goes around the loop.

In practise, these days I believe browsers have JS engines smart enough to optimise the performance impact of that look up away.

Sign up to request clarification or add additional context in comments.

5 Comments

For a price of additional variable.
But wouldn't reference the length member of an array be just as efficient as referencing n? i.e. they both need to be referenced in the same manner to extract the value.
@Guy — No. "Get n" is less work than "Get myArray, now get the legnth of it".
Even if the JS engines wasn't optimized wouldn't the lookup time be the same?
Did you know that you can't accept an answer on stack overflow if the question is less than 10 minutes old? :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.