Geeks With Blogs
Liam McLennan

JavaScript was created to add interactivity to Netscape 2.0 back in 1995. A consequence of this limited scope is that the language was given only a minimal standard library.

Should you ever try to solve a significant problem with JavaScript you will quickly feel the need for more advanced library methods than what JavaScript provides.


Underscore.js is a library of utility functions for JavaScript. Most of the functions add functional capabilities to JavaScript. Simply add a script reference to the underscore.js library and then access the functions directly off the _ variable (the functional style) or by wrapping a collection (array or object) with the _ function (the object oriented style).

Here are some examples:

// find the largest number. Functional style.
var largest = _.max([4,3,1,-9]);

// sort by relevance. OO style
var sorted = _([
  {name: "result 1", relevance: 7},
  {name: "result 2", relevance: 3}
]).sortBy(function(result) { 
  return result.relevance;

// count the words in a song. From 
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"}

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

Posted on Sunday, October 31, 2010 6:16 PM | Back to top

Copyright © Liam McLennan | Powered by: