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
}
Guy
  • 65,082
  • 97
  • 254
  • 325
  • 1
    http://jsperf.com/caching-array-length/4 – thefourtheye Mar 30 '14 at 14:44
  • 2
    The second is a syntax error: `expected ';'` – Bergi Mar 30 '14 at 14:47
  • possible duplicate of [Is reading the \`length\` property of an array really that expensive an operation in JavaScript?](http://stackoverflow.com/questions/5752906/is-reading-the-length-property-of-an-array-really-that-expensive-an-operation) and [Do modern JavaScript JITers need array-length caching in loops?](https://stackoverflow.com/questions/6261953/do-modern-javascript-jiters-need-array-length-caching-in-loops) – Bergi Mar 30 '14 at 14:48
  • @Bergi Yes, exact duplicate of both of those. Without knowing the answer it was impossible to search for those questions. What is the standard here. Should I delete this question? – Guy Mar 31 '14 at 17:48
  • Nah, if 5 people will vote for closing it will become tagged as a duplicate, that's enough. If you as the asker would, it should go pretty fast. – Bergi Mar 31 '14 at 20:55

1 Answers1

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.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • For a price of additional variable. – Shomz Mar 30 '14 at 14:46
  • 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 Mar 30 '14 at 14:46
  • @Guy — No. "Get n" is less work than "Get myArray, now get the legnth of it". – Quentin Mar 30 '14 at 14:47
  • Even if the JS engines wasn't optimized wouldn't the lookup time be the same? – Guy Mar 30 '14 at 14:47
  • Did you know that you can't accept an answer on stack overflow if the question is less than 10 minutes old? :) – Guy Mar 30 '14 at 14:48