Thursday, October 29th, 2009

Would you like a _ with that $? New library gives JS what it should have

Category: JavaScript, Library

<>p>Jeremy Ashkenas and the DocumentCloud team have just released Underscore.js a small library that provides all the functional programming helpers that you expect from Prototype.js or Ruby, but without extending any core JavaScript objects.

Jeremy told us:

This makes it a natural fit alongside jQuery, without having to worry about the conflicts and redundant functionality that using Prototype and jQuery together would entail. For browsers that support the new Javascript 1.6 array functions, it delegates to the native implementations, so your “_.map()” can run at full speed, where available. It’s a tiny download, 4k when gzipped. Here’s the project page, with full documentation, live tests and benchmarks.

Some of the utilities:

Collections
each, map,
reduce, 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, isElement,
isArray, isFunction, isUndefined

Utility

noConflict,
uniqueId, template

There has already been nice community patches and suggestions from the community, and Kris Kowal helped make it CommonJS-compliant.

Obviously, other libraries have covered a lot of these before, but it is nice to see a small core covering.

Related Content:

Posted by Dion Almaer at 12:50 am
21 Comments

+----
1.9 rating from 74 votes

21 Comments »

Comments feed TrackBack URI

Well, the underscore is kind of tricky, I already use it for translations with gettext for instance :)
(You can always use the .noConflict to get around it of course)

Comment by aadsm — October 29, 2009

i too use underscore as translation method — didn’t they knew, that it’s the shortcut function for gettext … ?

Comment by aurora — October 29, 2009

The worst of two worlds.

I mean, what kind of idiom is that, _.map([], f);? compare it with the real thing, [].map(f) and you’ll understand why using javascript’s OO features as well as functional features is much more elegant, less cryptic and useful also since you get to know how js really works and then you can make your own sort of framework or even dsl.

Comment by philogb — October 29, 2009

Great idea, really nice.

Comment by stoimen — October 29, 2009

I agree with philogb, and at the risk of starting a flaming fanboy war, would like to express that my personal preference is to make use of the native inheritance/prototypical nature of javascript in extending objects already present.

I know it’s not always a possibility to have complete control over the code environment of a site, but when I do; I like to extend the native prototypes, as there really is no harm or risk of conflicts in the global namespace or natives.

It’s all very well-intentioned in developing something global namespace friendly, but how well-intentioned is it building the means to allow for extraneous script inclusion? Why afford lazy developers the ability to pollute their sites with as many (plays well with others) frameworks as they can possibly jam into any given site? Surely talented developers should be of the mindset that only the essential scripts get included, in which case they should be free to make use of native extension as a means to clearly (and in a concise manner) create code swiftly that works well AND is easy to read.

Comment by sixtyseconds — October 29, 2009

Outstanding.

I also don’t think that developers should pollute their websites
with needless code they could do without, but this library here
is really simplified and packed with great features that can save
a lot of time for less-experienced developers.

Comment by vsync — October 29, 2009

Any reason the iterator protocol isn’t used?
http://bob.pythonmac.org/archives/2005/07/06/iteration-in-javascript/
https://developer.mozilla.org/en/New_in_JavaScript_1.7#Iterators

Although the operations in the lib are reasonable, IMHO “real” iterators are what truly unleashes functional programming.
See for example: http://mochikit.com/doc/html/MochiKit/Iter.html (+ similar Array ops in the Base module)

Comment by FredrikB — October 29, 2009

Another library, nothing new… Other than the not-so-ground-breaking idea of throwing everything beneath the _ namespace… Any JS developer worth his/her salt has already compiled their own mini-library of helper functions similar to these. Meh.

Comment by JimmyP22 — October 29, 2009

Agree with philogb, besides… if for some reason (and there ARE occasional reasons), I needed functional methods and keep native objects clean, I would just copy/paste the pattern I needed and stick it to $ or a ‘util’ namespace, just like jQuery is doing with ‘extend’.
.
Usually I choose the sugar.js solution where I extend native objects with SAFE methods and add new objects or namespaces for UNSAFE methods or just embed it into my project.js somewhere.
.
Using the $ has been justified and marginally accepted by now as it has a abstract generally accepted purpose. The underscore in this case is nothing more then a namespace for a library that wrongfully promotes functional programming in a OO language…
.
Swing and miss, but no loss, most of this library is copy/paste of patterns found abundantly on internet anyways.

Comment by BenGerrissen — October 29, 2009

Sorry to be one of the critics, dont let it put ya down.
Just remember:
- Dont solve problems that dont exists.
- Improve the wheel, dont reinvent it.
- Port the wheel if it doesn’t exist in your environment.
- Integrate the wheel into your project.
- Make sure you can replace your wooden wheel for a rubber one if someone else invents it.

Comment by BenGerrissen — October 29, 2009

“Why afford lazy developers the ability to pollute their sites with as many frameworks as they can possibly jam into any given site?” Namespace cleanliness isn’t always about developer-side framework inclusion. I do a lot of bookmarklet development, where you have to be prepared for anything, and can’t make any alterations to the browser environment you’re running in. This library is a perfect companion to jQuery for developing bookmarklet-based applications that have a zero namespace footprint.

“The underscore in this case is nothing more then a namespace for a library that wrongfully promotes functional programming in a OO language.” JavaScript’s first-class function and closure support make it every bit as much of a functional language as an OO language. Douglas Crockford has famously (and correctly) stated that JavaScript is closer to Lisp than to Java. Giving developers tools to leverage the functional nature of JS is NOT working against the grain of the language.

Comment by sentientholon — October 29, 2009

@sentientholon – bookmarklet development assumes that you don’t ship 3rd party code alongside code that has the desired effect of the bookmarklet, so it moots the use of any libraries…

I’m not talking about bookmarklet development in my above comment, since that obviously requires as little change to the environment as possible – I’m talking about making a library of your own code that isn’t afraid to alter the natives for ph33r of pissing off other libraries…

Comment by sixtyseconds — October 29, 2009

It’s nice work, Prototype without extending native prototypes. I’m hoping Prototype 2 will take this approach so we can all make code that’ll work for everyone.

Comment by Jadet — October 29, 2009

@jadet: … Hehe. That would kind of like defeat the purpose of Prototype – like jQuery tossing out all DOM related functionality or MooTools dropping the Class implementation…

Comment by rasmusfl0e — October 29, 2009

@rasmusfl0e: Not entirely, as far as the DOM goes syntax can be kept intact without extending by using wrappers. I’ve seen a number of working implementations using this http://groups.google.com/group/prototype-core/browse_thread/thread/c05add9fabd5a00c/
.
As far as not extending everything else, that’s a small price to pay for compatibility. It’s what’s holding Prototype back and probably why Underscore was created, you just have to play nice with jquery these days.

Comment by Jadet — October 29, 2009

It’s interesting to see how the general sentiment here has turned over time. It used to be that avoiding native prototypes was considered good practice and folks like Prototype were mocked for going against that grain. Now Underscore is mocked for following that (generally good) guidance? LOL.

I personally think that altering native prototypes is just fine, if you have a good handle on your environment and everyone touching the code knows what effect it’s going to have. I look at Underscore as a set of commonly used methods for an environment where altering native prototypes is not advised, in which case it’s both useful and powerful. And like most Javascript libraries, it’s just aimed at getting the most common stuff out of the way so that developers can focus on… developing software. It’s not groundbreaking in any way, but it’s certainly useful.

Comment by eyelidlessness — October 29, 2009

Looks pretty handy. And yes, JavaScript is as much functional as it is object oriented.

Comment by nathany — October 29, 2009

There’s a zip function but no unzip? Where are the foldl and foldr functions?!

Comment by pfhat — October 29, 2009

@jadet: What I gathered from your comment was that you wanted Prototype without the native prototypes… that wouldn’t be Prototype then clearly. :/

Take out the core parts of a js library philosophy and you’re left with a rather generic toolkit – if anything.

People should strive for _sane_ environments instead of scaling back on the usefullnes of js libraries – methinks.

Comment by rasmusfl0e — October 29, 2009

What I want is a scripty2 I can mashup with pre-existing jquery stuff without having to modify things. Would a port of the functional backend of scripty2 from Prototype to this emulator make that happen?

Comment by rdza — October 29, 2009

Pretty handy
thanks

Comment by Aphrodisiac — January 22, 2010

Leave a comment

You must be logged in to post a comment.