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.
// 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
// http://documentcloud.github.com/underscore/
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;
}, {}).value();