Underscore.js

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 provides 50-odd functions that support both the usual functional suspects: map, select, invoke — as well as more specialized helpers: function binding, javascript templating, deep equality testing, and so on. It delegates to built-in functions, if present, so JavaScript 1.6 compliant browsers will use the native implementations of forEach, map, filter, every, some and indexOf.

Underscore includes a complete Test & Benchmark Suite for your perusal.

The unabridged source code is available on GitHub.

Downloads (Right-click, and use "Save As")

Development Version (0.4.1) 18kb, Uncompressed with Comments
Production Version (0.4.1) 2kb, Packed and Gzipped

Object-Oriented and Functional Styles

You can use Underscore in either an object-oriented or a functional style, depending on your preference. The following two lines of code are identical ways to double a list of numbers.

_.map([1, 2, 3], function(n){ return n * 2; });
_([1, 2, 3]).map(function(n){ return n * 2; });

Using the object-oriented style allows you to chain together methods. Calling chain on a wrapped object will cause all future method calls to return wrapped objects as well. When you've finished the computation, use get to retrieve the final value. Here's an example of chaining together a map/flatten/reduce, in order to get the word count of every word in a song.

var lyrics = [
  {line : 1, words : "I'm a lumberjack and I'm okay"},
  {line : 2, words : "I sleep all night and I work all day"},
  {line : 3, words : "He's a lumberjack and he's okay"},
  {line : 4, words : "He sleeps all night and he works all day"}
];

_(lyrics).chain()
  .map(function(line) { return line.words.split(' '); })
  .flatten()
  .reduce({}, function(counts, word) {
    counts[word] = (counts[word] || 0) + 1;
    return counts;
}).get();

=> {lumberjack : 2, all : 4, night : 2 ... }

In addition, the Array prototype's methods are proxied through the chained Underscore object, so you can slip a reverse or a push into your chain, and continue to modify the array.

Table of Contents

Collections
each, map, reduce, reduceRight, detect, select, reject, all, any, include, invoke, pluck, max, min, sortBy, sortedIndex, toArray, size

Arrays
first, last, compact, flatten, without, uniq, intersect, zip, indexOf, lastIndexOf

Functions
bind, bindAll, delay, defer, wrap, compose

Objects
keys, values, extend, clone, isEqual, isEmpty, isElement, isArray, isFunction, isUndefined

Utility
noConflict, identity, breakLoop, uniqueId, template

Chaining
chain, get

Collection Functions (Arrays or Objects)

each_.each(list, iterator, [context]) Alias: forEach
Iterates over a list of elements, yielding each in turn to an iterator function. The iterator is bound to the context object, if one is passed. Each invocation of iterator is called with three arguments: (element, index, list). If list is a JavaScript object, iterator's arguments will be (value, key, list). Use breakLoop to break out of the iteration. Delegates to the native forEach function if it exists.

_.each([1, 2, 3], function(num){ alert(num); });
=> alerts each number in turn...

map_.map(list, iterator, [context])
Produces a new array of values by mapping each value in list through a transformation function (iterator). If the native map method exists, it will be used instead.

_.map([1, 2, 3], function(num){ return num * 3 });
=> [3, 6, 9]

reduce_.reduce(list, memo, iterator, [context]) Aliases: inject, foldl
Also known as inject and foldl, reduce boils down a list of values into a single value. Memo is the initial state of the reduction, and each successive step of it should be returned by iterator.

var sum = _.reduce([1, 2, 3], 0, function(memo, num){ return memo + num });
=> 6

reduceRight_.reduceRight(list, memo, iterator, [context]) Alias: foldr
The right-associative version of reduce. Delegates to the JavaScript 1.8 version of reduceRight, if it exists. Foldr is not as useful in JavaScript as it would be in a language with lazy evaluation.

var list = [[0, 1], [2, 3], [4, 5]];
var flat = _.reduceRight(list, [], function(a, b) { return a.concat(b); });
=> [4, 5, 2, 3, 0, 1]

detect_.detect(list, iterator, [context])
Looks through each value in the list, returning the first one that passes a truth test (iterator). The function returns as soon as it finds an acceptable element, and doesn't traverse the entire list.

var even = _.detect([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });
=> 2

select_.select(list, iterator, [context]) Alias: filter
Looks through each value in the list, returning an array of all the values that pass a truth test (iterator). Delegates to the native filter method, if it exists.

var evens = _.select([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });
=> [2, 4, 6]

reject_.reject(list, iterator, [context])
Returns the values in list without the elements that the truth test (iterator) passes. The opposite of select.

var odds = _.reject([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });
=> [1, 3, 5]

all_.all(list, [iterator], [context]) Alias: every
Returns true if all of the values in the list pass the iterator truth test. If an iterator is not provided, the truthy value of the element will be used instead. Delegates to the native method every, if present.

_.all([true, 1, null, 'yes']);
=> false

any_.any(list, [iterator], [context]) Alias: some
Returns true if any of the values in the list pass the iterator truth test. Short-circuits and stops traversing the list if a true element is found. Delegates to the native method some, if present.

_.any([null, 0, 'yes', false]);
=> true

include_.include(list, value)
Returns true if the value is present in the list, using === to test equality. Uses indexOf internally, if list is an Array.

_.include([1, 2, 3], 3);
=> true

invoke_.invoke(list, methodName, [*arguments])
Calls the method named by methodName on each value in the list. Any extra arguments passed to invoke will be forwarded on to the method invocation.

_.invoke([[5, 1, 7], [3, 2, 1]], 'sort');
=> [[1, 5, 7], [1, 2, 3]]

pluck_.pluck(list, propertyName)
An convenient version of what is perhaps the most common use-case for map: extracting a list of property values.

var stooges = [{name : 'moe', age : 40}, {name : 'larry', age : 50}, {name : 'curly', age : 60}];
_.pluck(stooges, 'name');
=> ["moe", "larry", "curly"]

max_.max(list, [iterator], [context])
Returns the maximum value in list. If iterator is passed, it will be used on each value to generate the criterion by which the value is ranked.

var stooges = [{name : 'moe', age : 40}, {name : 'larry', age : 50}, {name : 'curly', age : 60}];
_.max(stooges, function(stooge){ return stooge.age; });
=> {name : 'curly', age : 60};

min_.min(list, [iterator], [context])
Returns the minimum value in list. If iterator is passed, it will be used on each value to generate the criterion by which the value is ranked.

var numbers = [10, 5, 100, 2, 1000];
_.min(numbers);
=> 2

sortBy_.sortBy(list, iterator, [context])
Returns a sorted list, ranked by the results of running each value through iterator.

_.sortBy([1, 2, 3, 4, 5, 6], function(num){ return Math.sin(num); });
=> [5, 4, 6, 3, 1, 2]

sortedIndex_.sortedIndex(list, value, [iterator])
Uses a binary search to determine the index at which the value should be inserted into the list in order to maintain the list's sorted order. If an iterator is passed, it will be used to compute the sort ranking of each value.

_.sortedIndex([10, 20, 30, 40, 50], 35);
=> 3

toArray_.toArray(list)
Converts the list (anything that can be iterated over), into a real Array. Useful for transmuting the arguments object.

(function(){ return _.toArray(arguments).slice(0); })(1, 2, 3);
=> [1, 2, 3]

size_.size(list)
Return the number of values in the list.

_.size({one : 1, two : 2, three : 3});
=> 3

Array Functions

first_.first(array)
Convenience to return the first element of an array (identical to array[0]).

_.first([3, 2, 1]);
=> 3

last_.last(array)
Returns the last element of an array.

_.last([3, 2, 1]);
=> 1

compact_.compact(array)
Returns a copy of the array with all falsy values removed. In JavaScript, false, null, 0, "", undefined and NaN are all falsy.

_.compact([0, 1, false, 2, '', 3]);
=> [1, 2, 3]

flatten_.flatten(array)
Flattens a nested array (the nesting can be to any depth).

_.flatten([1, [2], [3, [[[4]]]]]);
=> [1, 2, 3, 4];

without_.without(array, [*values])
Returns a copy of the array with all instances of the values removed. === is used for the equality test.

_.without([1, 2, 1, 0, 3, 1, 4], 0, 1);
=> [2, 3, 4]

uniq_.uniq(array, [isSorted])
Produces a duplicate-free version of the array, using === to test object equality. If you know in advance that the array is sorted, passing true for isSorted will run a much faster algorithm.

_.uniq([1, 2, 1, 3, 1, 4]);
=> [1, 2, 3, 4]

intersect_.intersect(*arrays)
Computes the list of values that are the intersection of all the arrays. Each value in the result is present in each of the arrays.

_.intersect([1, 2, 3], [101, 2, 1, 10], [2, 1]);
=> [1, 2]

zip_.zip(*arrays)
Merges together the values of each of the arrays with the values at the corresponding position. Useful when you have separate data sources that are coordinated through matching array indexes.

_.zip(['moe', 'larry', 'curly'], [30, 40, 50], [true, false, false]);
=> [["moe", 30, true], ["larry", 40, false], ["curly", 50, false]]

indexOf_.indexOf(array, value)
Returns the index at which value can be found in the array, or -1 if value is not present in the array. Uses the native indexOf function unless it's missing.

_.indexOf([1, 2, 3], 2);
=> 1

lastIndexOf_.lastIndexOf(array, value)
Returns the index of the last occurrence of value in the array, or -1 if value is not present. Uses the native lastIndexOf function if possible.

_.lastIndexOf([1, 2, 3, 1, 2, 3], 2);
=> 4

Function (uh, ahem) Functions

bind_.bind(function, context, [*arguments])
Bind a function to a context object, meaning that whenever the function is called, the value of this will be the context. Optionally, bind arguments to the function to pre-fill them, also known as currying.

var func = function(greeting){ return greeting + ': ' + this.name };
func = _.bind(func, {name : 'moe'}, 'hi');
func();
=> 'hi: moe'

bindAll_.bindAll(*methodNames, context)
Binds a number of methods on the context object, specified by methodNames, to be run in the context of that object whenever they are invoked. Very handy for binding functions that are going to be used as event handlers, which would otherwise be invoked with a fairly useless this.

var buttonView = {
  label   : 'underscore',
  onClick : function(){ alert('clicked: ' + this.label); },
  onHover : function(){ console.log('hovering: ' + this.label); }
};
_.bindAll('onClick', 'onHover', buttonView);
jQuery('#underscore_button').bind('click', buttonView.onClick);
=> When the button is clicked, this.label will have the correct value...

delay_.delay(function, wait, [*arguments])
Much like setTimeout, invokes function after wait milliseconds. If you pass the optional arguments, they will be forwarded on to the function when it is invoked.

var log = _.bind(console.log, console);
_.delay(log, 1000, 'logged later');
=> 'logged later' // Appears after one second.

defer_.defer(function)
Defers invoking the function until the current call stack has cleared, similar to using setTimeout with a delay of 0. Useful for performing expensive computations or HTML rendering in chunks without blocking the UI thread from updating.

_.defer(function(){ alert('deferred'); });
// Returns from the function before the alert runs.

wrap_.wrap(function, wrapper)
Wraps the first function inside of the wrapper function, passing it as the first argument. This allows the wrapper to execute code before and after the function runs, adjust the arguments, and execute it conditionally.

var hello = function(name) { return "hello: " + name; };
hello = _.wrap(hello, function(func) {
  return "before, " + func("moe") + ", after";
});
hello();
=> 'before, hello: moe, after'

compose_.compose(*functions)
Returns the composition of a list of functions, where each function consumes the return value of the function that follows. In math terms, composing the functions f(), g(), and h() produces f(g(h())).

var greet    = function(name){ return "hi: " + name; };
var exclaim  = function(statement){ return statement + "!"; };
var welcome = _.compose(greet, exclaim);
welcome('moe');
=> 'hi: moe!'

Object Functions

keys_.keys(object)
Retrieve all the names of the object's properties.

_.keys({one : 1, two : 2, three : 3});
=> ["one", "two", "three"]

values_.values(object)
Return all of the values of the object's properties.

_.values({one : 1, two : 2, three : 3});
=> [1, 2, 3]

extend_.extend(destination, source)
Copy all of the properties in the source object over to the destination object.

_.extend({name : 'moe'}, {age : 50});
=> {name : 'moe', age : 50}

clone_.clone(object)
Create a shallow-copied clone of the object. Any nested objects or arrays will be copied by reference, not duplicated.

_.clone({name : 'moe'});
=> {name : 'moe'};

isEqual_.isEqual(object, other)
Performs an optimized deep comparison between the two objects, to determine if they should be considered equal.

var moe   = {name : 'moe', luckyNumbers : [13, 27, 34]};
var clone = {name : 'moe', luckyNumbers : [13, 27, 34]};
moe == clone;
=> false
_.isEqual(moe, clone);
=> true

isEmpty_.isEmpty(object)
Returns true if object contains no values.

_.isEmpty([1, 2, 3]);
=> false
_.isEmpty({});
=> true

isElement_.isElement(object)
Returns true if object is a DOM element.

_.isElement(jQuery('body')[0]);
=> true

isArray_.isArray(object)
Returns true if object is an Array.

(function(){ return _.isArray(arguments); })();
=> false
_.isArray([1,2,3]);
=> true

isFunction_.isFunction(object)
Returns true if object is a Function.

_.isFunction(alert);
=> true

isUndefined_.isUndefined(variable)
Returns true if variable is undefined.

_.isUndefined(window.missingVariable);
=> true

Utility Functions

noConflict_.noConflict()
Give control of the "_" variable back to its previous owner. Returns a reference to the Underscore object.

var underscore = _.noConflict();

identity_.identity(value)
Returns the same value that is used as the argument. In math: f(x) = x
This function looks useless, but is used throughout Underscore as a default iterator.

var moe = {name : 'moe'};
moe === _.identity(moe);
=> true

breakLoop_.breakLoop()
Breaks out of the current loop iteration. Similar to the break keyword in regular "for" loop, but works within an iterator function.

var result = null;
_.each([1, 2, 3], function(num) { 
  if ((result = num) == 2) _.breakLoop(); 
});
result;
=> 2

uniqueId_.uniqueId([prefix])
Generate a globally-unique id for client-side models or DOM elements that need one. If prefix is passed, the id will be appended to it.

_.uniqueId('contact_');
=> 'contact_104'

functions_.functions([prefix]) Alias: methods
Returns a sorted list of the name of every function in Underscore.

_.functions();
=> ["all", "any", "bind", "bindAll", "clone", "compact", "compose" ...

template_.template(templateString, [context])
Compiles JavaScript templates into functions that can be evaluated for rendering. Useful for rendering complicated bits of HTML from JSON data sources. Template functions can both interpolate variables, using
<%= … %>, as well as execute arbitrary JavaScript code, with <% … %>. When you evaluate a template function, pass in a context object that has properties corresponding to the template's free variables. If you're writing a one-off, you can pass the context object as the second parameter to template in order to render immediately instead of returning a template function.

var compiled = _.template("hello: <%= name %>");
compiled({name : 'moe'});
=> "hello: moe"

var list = "<% _.each(people, function(name) { %> <li><%= name %></li> <% }); %>";
_.template(list, {people : ['moe', 'curly', 'larry']});
=> "<li>moe</li><li>curly</li><li>larry</li>"

Chaining

chain_(obj).chain()
Returns a wrapped object. Calling methods on this object will continue to return wrapped objects until get is used. ( A more realistic example.)

var stooges = [{name : 'curly', age : 25}, {name : 'moe', age : 21}, {name : 'larry', age : 23}];
var youngest = _(stooges).chain()
  .sortBy(function(stooge){ return stooge.age; })
  .map(function(stooge){ return stooge.name + ' is ' + stooge.age; })
  .first()
  .get();
=> "moe is 21"

get_(obj).get()
Extracts the value of a wrapped object.

_([1, 2, 3]).get();
=> [1, 2, 3]

Change Log

0.4.1
Chained Underscore objects now support the Array prototype methods, so that you can perform the full range of operations on a wrapped array without having to break your chain. Added a breakLoop method to break in the middle of any Underscore iteration. Added an isEmpty function that works on arrays and objects.

0.4.0
All Underscore functions can now be called in an object-oriented style, like so: _([1, 2, 3]).map(...);. Original patch provided by Marc-André Cournoyer. Wrapped objects can be chained through multiple method invocations. A functions method was added, providing a sorted list of all the functions in Underscore.

0.3.3
Added the JavaScript 1.8 function reduceRight. Aliased it as foldr, and aliased reduce as foldl.

0.3.2
Now runs on stock Rhino interpreters with: load("underscore.js"). Added identity as a utility function.

0.3.1
All iterators are now passed in the original collection as their third argument, the same as JavaScript 1.6's forEach. Iterating over objects is now called with (value, key, collection), for details see _.each.

0.3.0
Added Dmitry Baranovskiy's comprehensive optimizations, merged in Kris Kowal's patches to make Underscore CommonJS and Narwhal compliant.

0.2.0
Added compose and lastIndexOf, renamed inject to reduce, added aliases for inject, filter, every, some, and forEach.

0.1.1
Added noConflict, so that the "Underscore" object can be assigned to other variables.

0.1.0
Initial release of Underscore.js.

A DocumentCloud Project