Contrary to some of the statements below, the length of an Array is not calculated on each iteration. The length of an Array is a property which is set by modifying operations such as pop
, push
, shift
, unshift
, splice
and so forth.
You will see a minor performance hit though since a property lookup has a higher cost than a local variable. Therefore caching the length is a good idea. However you won't see a big difference unless you are dealing with huge datasets.
There is a special case though where the length is indeed calculated on each iteration. This is the case with HTML node collections. Since these are live objects, the length is not a property in the sense it is with an array. If you do this:
for (var i=0; i < collection.length; i++) {
collection[i]
};
Then the collection is parsed on each iteration.
As for optimizing a for loop, I usually use these techniques for caching:
// if order is of no concern, just iterate from length-1 to 0
for (var i = arr.length - 1; i >= 0; i--){
arr[i]
};
// use the for loop statement to set up scoped variables
for (var i=0, length = arr.length; i < length; i++) {
// do something
}