Last Updated: February 25, 2016
·
2.368K
· 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.

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Related Tags
#javascript
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside