I was browsing around and I found this:
var i, len;
for(i = 0, len = array.length; i < len; i++) {
//...
}
My first thoughts are:
- Why he did that? (it must be better for some reason)
- Is it worth it? (I assume yes, why else he will do it this way?)
Do normal loops (the ones that don’t cache the length) check the array.length each time?
A loop consisting of three parts is executed as follows:
So, yes: The
.lengthproperty of an array is checked at each enumeration if it’s constructed asfor(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++) { ... }: