Skip to main content
Home / Code Snippets / JavaScript / Loop Through Array Without Wasteful Lookups

Loop Through Array Without Wasteful Lookups

Find the length of the array before using it in the for function, so it doesn't need to count the length of the array each iteration (assuming the length won't be changing mid-loop).

var arLen=myArray.length;

for ( var i=0, len=arLen; i<len; i++ ){
  // do something with myArray[i]
}
icon-link icon-logo-star icon-search icon-star