Do loops check the array.length every time when comparing i against array.length?

A loop consisting of three parts is executed as follows:

for (A; B; C)

A - Executed before the enumeration
B - condition to test
C - expression after each enumeration (so, not if B evaluated to false)

So, yes: The .length property of an array is checked at each enumeration if it’s constructed as for(var i=0; i<array.length; i++). For micro-optimisation, it’s efficient to store the length of an array in a temporary variable (see also: What’s the fastest way to loop through an array in JavaScript?).

Equivalent to for (var i=0; i<array.length; i++) { ... }:

var i = 0;
while (i < array.length) {
    ...
    i++;
}

Leave a Comment