September 08

Bad ways to loop in JavaScript

Date: September 08, 2009. Comments»

Hope you might have read my previous article Associate array are bad in Javascript, let me get in one step further beside associate array, what are the bad ways to loop a DOM, array, node list in JavaScript. Some of the Bad ways:

1. for (var i=0; i < arr.length; i++) {}
2. while (x = arr.pop()) {}
3. while (x = arr.pop()) {}
4. for (var i in arr) {} (this is the worst, remember JavaScript is not Python :p)
5. for (var i=0; arr[i]; i++) { var x = arr[i]; }
Better way:
for (var i=0, len=arr.length; i < len; i++) {}

Length of a HTML collection is expensive

Remember every DOM operation that you make is expensive so think of ways you can minimize. When are trying to do DOM operation like looping on a HTML collection with length its live during your looping user might make some change which might change the length of the collection. So, the better way is to avoid the length.

People are so used to JavaScript libraries and try to do array.item(i) rather than doing doing array[i], array[i] is like a hash value so its pretty fast, array.item(i) is a bad way.
for (var i=0, node; node = collection[i++];) {}

Comments

Prashanth - September 09, 2009.
@Rakesh Pai thanks for enlightening me. Its true that there are many more ways to loop but those I mentioned here are one which I feel most commonly used. I am looking forward to your blog post.
Rakesh Pai - September 09, 2009.
While you are right that DOM operations are expensive, and that pre-computing the array length is generally an optimization (DOM or otherwise), you are wrong about the fact that the user can change the length in the course of the execution of the loop. This is because JS is single-threaded. Once the code is being executed, it blocks the UI thread. Any user operation, or for that matter any operation at all, gets stacked up, and executed after your code has finished execution. So, for all practical purposes, the length can be considered immutable. Of course this is not true if you are changing the length of the collection itself inside the loop, or if you are relinquishing control of the thread by calling setTimeout / setInterval. These will generally cause bigger problems, and a for loop as an iterator is generally not suitable here. There are several other ways to loop other than the ones you've mentioned here. I've prepared a test suite to gauge performance of looping, and have some interesting results. Will share it on my blog soon.
Leave Comment: