Expand your utility belt with Underscore.js

The JavaScript library Underscore.js streamlines tasks and allows you to do more with fewer lines of code. Get a sense of what you can do with some of its 60+ functions.

The number of JavaScript libraries freely available across the web can be a bit overwhelming, but there are several you should add to your toolbox for current or upcoming projects — one of which is Underscore.js. This library extends the base functionality of JavaScript, providing things we wished were a part of the core JavaScript language. Here's a look at some of the common applications of Underscore.js.

Not just another library

A coworker raised his hand (the stop sign) when I brought up Underscore.js. Basically, he told me he has enough JavaScript libraries to do everything he needs. While this is technically true, the beauty of Underscore.js is the streamlining of tasks. It provides a lot of the functional programming support found in a language such as Ruby; it also provides basic functions that simplify working with data.

It does not necessarily compete with other libraries or frameworks like jQuery, although there is some overlap. The focus of jQuery is the front-end or DOM. You can use another library like Backbone.js to organize your code (as a side note, Backbone.js utilizes Underscore.js). For example, all three of these live in harmony, streamlining and enhancing development.

Underscore.js is free. You download the JavaScript source file, include it in your web page or other JavaScript code, and you are up and running with it. One of the nicer features of Underscore.js is its size — the compressed and minified version is approximately 4 KB, which results in minimal impact of page load times. You can use the full development version to get a look at its design and coding.

What it provides

The details of the Underscore.js library are beyond the scope of this post, though we can cover its core features. The 60+ functions provided by Underscore.js are organized into these categories of what they manipulate: arrays, collections (JavaScript associative arrays), functions, and objects. Also, Underscore.js provides numerous utility functions, with templating receiving the most attention.

Like the dollar sign ($) in jQuery, Underscore.js uses the underscore character (_). All Underscore.js methods are wrapped inside a single function identified by the underscore (_); this allows you to utilize features globally with the underscore (_). The complete list of available functions is beyond this post, but we'll look at a few of them.

Working with numbers or a group of numbers is common. The following snippet shows some of the Underscore.js functions that simplify tasks. The min function returns the minimum value in a list, the max function does the opposite. Notice the underscore character is followed by the list variable in parentheses followed by a call to functions. The intersection function is interesting, as it accepts two or more lists as parameters and returns a list of values common to all of the lists. I have this code running in a browser, so I use alert to display the results — you can easily use console.log.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head><title>TechRepublic - underscore.js example</title>

<script src="underscore-min.js" type="text/javascript"></script>


<script type="text/javascript">

var hits = [5, 35, 17, 1000, 345, 300, 2, 900];

var hits2 = [15, 56, 100, 102, 345, 301, 12, 900];

alert (_(hits).min());
alert (_(hits).max());
alert (_.intersection(hits, hits2));

The range function is available to set up a list of numbers — it accepts a starting number, an ending number, and an increment value, so the following code sets up a list with values 100,200,300.

var hitRange = _.range(100, 400, 100);

Numbers are good, but working with collections and often string values is the focus of most client-side development (or maybe that is just me). The Underscore.js library provides a large number of functions for working with strings. The following snippet uses the isString function to determine if the value passed to it is a string. I have quickly fallen in love with this function.

var myVar = 'string value';
if (_.isString(myVar)) { alert('Yes'); }

There is a list of these function for checking values/objects — isEmpty, isArray, isNumber, and isBoolean are just a few examples. Working with lists of values is supported with numerous functions. The keys and values functions return their respective values when passed a list.

var names = ['Tony', 'Mary', 'Sonja', 'Jody'];

The pluck function allows you to extract certain items from key/value list pairs — pass it the name and that part of the list is pulled out to create a new list. Another great function called map allows you to manipulate each value in a list — you call map on the list and pass in a function that does what you need to do to the list values. In the example below, text is prepended to the link values from the list.

var articles = [{title : 'Include data in ASP.NET pages with data binding', link : 'http://www.techrepublic.com/article/include-data-in-aspnet-pages-with-data-binding/6092251'},

{title : 'Embrace the JSON standard in your C# code', link : 'http://www.techrepublic.com/blog/programming-and-development/embrace-the-json-standard-in-your-c-code/6684'},

{title : 'Spell-check .NET applications with NHunspell', link : 'http://www.techrepublic.com/blog/programming-and-development/spell-check-net-applications-with-nhunspell/6567'}];

var titles = _.pluck(articles, 'title'); // pull out the titles

var links = _.pluck(articles, 'link'); // pull out article links

var newLinks = _(links).map(function(val){return 'Follow this link -> ' + val});



While you can call methods individually, the Underscore.js library supports chaining as well, so you can accomplish multiple actions with one line.

One of the more interesting and publicized pieces of Underscore.js is templates, but I have not had the chance to dig into this feature at this point. The Underscore.js documentation provides plenty of information.

Do I really need it?

If you use Backbone.js, you already have Underscore.js, so no worries about adding it to your application; otherwise, you need to download and include it, so the many functions are easily within reach. One of the key aspects of Underscore.js that sold it for me is increasing productivity — do more with less code. Furthermore, less code hopefully means more readable code (or less to read).

Does this mean Underscore.js is good for you? Not necessarily, as it is important to consider the kind of work you are doing. If you are focusing on front-end development (aka the DOM), Underscore.js may not provide much you don't already have with a library like jQuery. On the other hand, if you are working with data like Twitter feeds, the many features of Underscore.js can be helpful.

The Underscore.js library isn't essential, as you can get things done with standard JavaScript, but why reinvent the wheel? Kick the tires on Underscore.js to see if it is beneficial for your current and future projects.

Keep your engineering skills up to date by signing up for TechRepublic's free Software Engineer newsletter, delivered each Tuesday.