Open-Source Spotlight: Underscore.js

JavaScript is a powerful language, but it lacks some of the handy utilities that developers of other languages like Ruby & Python have come to know and love. Underscore.js is your utility belt. In the author’s own words:

Underscore is a utility-belt library for JavaScript that provides a lot of the functional programming support that you would expect in Prototype.js (or Ruby), but without extending any of the built-in JavaScript objects. It’s the tie to go along with jQuery’s tux.

Underscore.js provides collection functions like each, map, include, and reduce. It makes arrays more powerful by adding flatten, uniq, and intersect. It extends objects with many useful functions like keys, values, functions, isNaN, and many more.

A few examples to whet your appetite:

Using the each function to write each array value to the console:

// object-oriented way
_(['John', 'Paul', 'George', 'Ringo']).each(function(beatle) {
    console.log(beatle);
});
// functional way
_.each(['John', 'Paul', 'George', 'Ringo'], function(beatle) {
    console.log(beatle);
});

Using the reduce method to round three numbers down and sum the results:

_.reduce([1.5,2,3.7], 0, function(memo, num) { return memo + Math.floor(num) });
// => 6

Using the pluck method to to extract just the names from an array of objects:

var beatles = [
  {name: 'John', dead: true},
  {name: 'Paul', dead: false},
  {name: 'Ringo', dead: false},
  {name: 'George', dead: true}
]

_.pluck(beatles, 'name');
// => ["John", "Paul", "Ringo", "George"]

The library weighs in at just 2.5kb once packed and gzipped, so there is little excuse not to take advantage of its offerings. There are over 60 functions included, the documentation on how to use each function is great, the source code is freely available on GitHub, and the library is completely DOM-free which means you can use it server-side as well.

Thanks to Jeremy Ashkenas and the folks at DocumentCloud for a great open-source library that we can all benefit from!

Jerod Santo is an Editor at Fuel Your Coding and a contract software developer at RSDi where he works daily with Ruby, JavaScript, and related technologies. He loves shiny toys, powerful tools, and open-source software. Learn more about Jerod by visiting his homepage or following him on Twitter.

 

If you liked this article, please help spread the news on the following sites:

  • Bump It
  • Blend It
  • Bookmark on Delicious
  • Stumble It
  • Float This
  • Reddit This
  • Share on FriendFeed
  • Clip to Evernote