Recently, I was looking for a way to do a task N times in JavaScript (like Ruby's N.times
method), which I found (_.times
) in the Underscore.js library. This discovery exposed me to an alternate way to call the Underscore methods, using its chaining syntax.
If you do a lot of work with Backbone, this syntax will be familiar. In Backbone, you can call many of the Underscore methods on models and collections:
bookCollection.each( function(model) { console.log( model.get('name') ); }); // >> 'American Gods' // >> 'Anansai Boys' // >> 'Coraline'
But what might not be obvious is that if you want to iterate over an object with Underscore, you can do the following:
_(["American Gods", "Anansi Boys", "Coraline"]).each( function(book) { console.log(book); }); // >> 'American Gods' // >> 'Anansai Boys' // >> 'Coraline'
Which is the same as doing this:
_.each(["American Gods", "Anansi Boys", "Coraline"], function(book) { console.log(book); } // >> 'American Gods' // >> 'Anansai Boys' // >> 'Coraline'
This becomes beneficial if you're working on a Backbone project and have a non-Backbone object that you want to iterate over. Going from collection.each(function(){})
to _.each(objs, function(){})
can be jarring, while _(objs).each(function(){})
is less confusing due to its similiarity.
Ready to build an industry-changing product?
Let's talk about your project today >>