_.each vs for

February 22nd 2013 by Samuel Rossille

I use the underscore library a lot when I write Javascript. So I whenever I have to iterate over an array, I have two ways of doing it. Using _.each:

_.each(myArray, function(element, index) {
    // whatever
}, this);

or a good old for loop:

var length = myArray.length;
for(var index = 0; index < length; index++) {
    var element = myArray[index];
    // whatever
};

The _.each loop has many advantages:

The for loop has the advantage of looking like the for loop of many other language. But I don't think that's an important point. Developpers are mentally agile people, and getting used to a syntax they have not met before is not such a big deal.

OK, but what about performance ? Code lisibility is important, but sometimes performance is even more important...

Well if the the application is starving for CPU power and a significant part of the CPU cost is in the array iterations, you might prefer for loops, but those conditions are not often met in real life application. Unless the application's business require heavy calculations on the client, chances are that most of the CPU cost is in DOM manipulation and reflows.

Good explainations on Array.forEach can be found on MDN, with fallback implementations as well.