DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world
Loop Through An Array Without Wasteful Lookups
Looking up the length of an array on each iteration of a loop is slow and inefficient (if the length of the array isn't changing).
If it's OK to iterate from back to front:
for ( var i=myArray.length-1; i>=0; --i ){
...
}If you need to go from front to back:
for ( var i=0, len=myArray.length; i<len; ++i ){
...
}




Comments
Snippets Manager replied on Wed, 2011/07/20 - 11:38pm
for ( var i=0, len=myArray.length; i So I just changed it to:for ( var i=0, i And it fixed the error. I'll deal with optimizations in the later stages.Greg Nonya replied on Wed, 2006/07/19 - 4:56pm
var arLen=myArray.length; for ( var i=0, len=arLen; i It is as efficient as back to front iter. and it keeps items in order they have been addedSnippets Manager replied on Mon, 2006/07/03 - 1:30pm