Underscore.js

Coming from a more technical backend role, and moving into JavaScript many people tend to look for very common functions to make their life easier. However, since JavaScript is considered a “functional” programming language, most of those little conveniences are currently unsupported. So I went searching a bit. Turns out there is a nice little utility belt library that gives us access to all of those built-in methods we all take for granted and are about to be supported in ECMAScript 5.





As the guys over at Underscore.js put it:

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 uses the built in functions if they exist, and if they don’t falls back to its own version. Since there are only a few browsers that currently support ECMAScript 5, it allows us to use these functions even on older browsers.  Now, not only can we start using those constructs before they are officially supported in the browsers, but as soon as they become available underscore.js will get out of the way.

Here is the current list of who supports ECMAScript 5 and which calls are supported: http://kangax.github.com/es5-compat-table/ At the time of this writing it looks like underscore wouldn’t even be needed in IE9, FF4, Chrome 7,8,9 and is only partialy needed in Opera 10.5-11.

Another key point about underscore.js is they do NOT extend any of the built in JavaScript objects. That means, all your existing objects will continue to work as expected. You won’t have to worry about underscore.js adding methods to some of your current objects:


var someArray = [1, 2, 3];

for (var i in someArray){
//do something to someArray[i]
}

We don’t need to worry that someArray will now contain a new function that would be returned in the loop. Couple that with all of the new features we can now use, and this looks like a win/win for Frontend Engineers.

Lets take a look at some of the things we get with the library:

Object-Oriented and Functional Styles

Collections

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

Arrays

first, rest, last, compact, flatten, without, uniq, intersect, zip, indexOf, lastIndexOf, range

Functions

bind, bindAll, memoize, delay, defer, throttle, debounce, wrap, compose

Objects

keys, values, functions, extend, clone, tap, isEqual, isEmpty, isElement, isArray, isArguments, isFunction, isString, isNumber, isBoolean, isDate, isRegExp isNaN, isNull, isUndefined

Utility

noConflict, identity, times, mixin, uniqueId, template

Chaining

chain, value

Pasted from <http://documentcloud.github.com/underscore/>

There are a couple of things I want to quickly look at. First, how are they making sure that we use the built-in method if it exists, and second… does that say template?

So Lets take a quick look at the _.each() function to see how they use built-in functions if they exist.


// The cornerstone, an `each` implementation, aka `forEach`.
// Handles objects implementing `forEach`, arrays, and raw objects.
// Delegates to **ECMAScript 5**'s native `forEach` if available.
var each = _.each = _.forEach = function(obj, iterator, context) {
var value;
if (obj == null) return;
if (nativeForEach && obj.forEach === nativeForEach) {
obj.forEach(iterator, context);
} else if (_.isNumber(obj.length)) {
for (var i = 0, l = obj.length; i < l; i++) {
if (iterator.call(context, obj[i], i, obj) === breaker) return;
}
} else {
for (var key in obj) {
if (hasOwnProperty.call(obj, key)) {
if (iterator.call(context, obj[key], key, obj) === breaker) return;
}
}
}
};

So if we look a bit more into what they are doing, it looks like they check to see if the object has a function called .forEach(); if it does, use the built-in function, otherwise figure out if it’s an array or object.

As for the second item in this list. I am going to devote another post just to templates, how we can use them and make them a bigger part of our frontend projects.

6 thoughts on “Underscore.js

      1. Diego

        Sorry I have actually noticed I did not scrolled the bar completely to reach JQuery templates :)
        Than I will definitively have a look at it :)

        Reply
      2. Diego

        Thanks a lot for the link! I see Jquery template engine performs even better than Mustache, I am going to try it, maybe together with Knockout.js

        Reply
  1. Diego

    Hi JC, thanks a lot for the link!
    I am happy to see Mustache provides far most the best performances :)
    I am very happy with it and maybe I will not evaluate alternatives for the moment :)

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>