September 08
Bad ways to loop in JavaScript
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:
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]; }
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.
Comments