Using Underscore.js

Although jQuery provides a number of utility methods that can make your life easier when writing JavaScript, the main focus of jQuery is to modify the DOM and provide simplified Ajax support. It doesn’t provide a lot of utility methods for other purposes. (jQuery does provide some, though; see http://api.jquery.com/category/utilities/ for some examples.)

Luckily, there’s a library called the Underscore.js that was created for just that purpose. Underscore is a small library (under 4 kb minified and gzipped) that provides approximately 60 methods that can make your JavaScript easier to understand and more compact.

Accessing Underscore

Underscore.js is included in your project as a single JavaScript file, much like jQuery. Also similar to jQuery, the author made the decision not to pollute the existing JavaScript namespace but rather to wrap all the methods inside of a single function identified, not surprisingly, by the underscore character, "_".

You can call underscore methods in two ways either in a functional or an object-oriented style. Following is an example of each:

_.isString(myVar);
_(myVar).isString();

The functional method calls the function directly on the underscore object, whereas the OO method first calls the underscore on the target (much like jQuery does with selectors) and then calls the method on the resulting object.

Working with Collections

The bulk of the methods in Underscore.js are targeted at working with collections, whether they are ...

Get Professional HTML5 Mobile Game Development now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.