Last Updated: February 25, 2016
·
2.152K
· nickjacob

javascript for loop idiom

I guess because javascript has such a C-syntax it's really tempting to always use the corresponding C idiom in js. It's true that you shouldn't use

for(var a in array){ ... }

for an array, but did you know that javascript lets you optimize in-the-loop in a way that you can't do as easily in C?

for(var i=0,l=array.length;i<l;i++){
     // do something
}

So you can reduce the array.length lookups (especially useful for deeply-nested length properties) in the declaration of the for loop.

I guess this isn't a widely-used idiom because it can be confusing for someone coming to js from another language.