Activate your free membership today | Log-in

Thursday, October 29th, 2009

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

Category: JavaScript, Library

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.

Posted by Dion Almaer at 12:50 am
27 Comments

+----
1.9 rating from 67 votes

27 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

WZZ

cheap wow gold Nigerian Ministry cheap wow gold of Communications aion gold and China signed
metin2 yang a supplementary
aion4gold agreement to Aion Kina the railway

Comment by WZZZ — November 3, 2009

One day in Aprila man standing in the streets of New York, pulled out a brick of about two big mobile phone, and began to talk. This person is the inventor of mobile phones Martin.Empire Spagetti Organza Wedding Dress Library Park – when he was Motorola’s engineering and technical personnel. This was one the world’s firstMermaid Allover Lace Satin Wedding Dress mobile phone.the U.S. Federal Communications Commission (FCC) to inexpensive bridesmaid dressesdetermine the land mobile telephone communications,and high-capacity cellular column wedding dressesmobile phone spectrum for mobile phones commercially ready. In 1979, Japan opened the world’s first cellular telephone network. In 1982 established the European GSM (Mobile Communications Special Section) in the first in the modern sense could be commercially available mobile phone was born.Empire Pleated Satin Chiffon Wedding DressIt is the power supply and antenna placed in a box, weighing about 3 kg.Shape close to the modern mobile phone, you was born in 1987. Its weight is still about 750 grams, with today’s cell phone weighs just 60 grams compared to, like a big brick.wedding dress

Comment by wuwei — November 9, 2009

will notpass Rolex shop until Replica Watches there is Replica Handbagsan invigorating Designer Handbagsautumn of endoscope freedom andequality. nineteen Replica Rolexsixty-three Gucciis not an end, but a beginning.those who hope that the negro needed to

Comment by qqlovee — December 7, 2009

The Windows 7 key is a usually unique, alphanumeric code of any length required by many software programs during installation. Unique windows 7 product key help software manufacturers ensure that each copy of their software was legally purchased. Windows 7 Home key | Windows 7 Professional key | Windows 7 Ultimate key | Windows 7 Enterprise key | Windows 7 Home Premium key

The unique Windows 7 serial key entered for an operating system or a software program is typically stored in an encrypted format in the Windows Registry, making finding one very difficult without some help. The above linked guides should help find just about any Windows 7 CD key you may be looking for.Windows 7 Home product key | Windows 7 Professiona productl key | Windows 7 Ultimate product key

This Windows 7 product serial number, if it exists, is the generic Windows 7 Home product key that Microsoft allowed your PC builder to use when mass producing computers. In other words, everyone’s disc has the same product key. Your unique key for use when reinstalling Windows will be the one on the sticker on your computer. Windows 7 Enterprise key | Windows 7 Home Premium key

Comment by luckey001 — January 19, 2010

Pretty handy
thanks

Comment by Aphrodisiac — January 22, 2010

louis vuitton has gained and maintained its leading position over the past decades as a brand name of luxuries goods in the world fashion industry.
louis vuitton Designer handbags symbolize both the social status and noble elegance
louis vuitton

Comment by wwwwwww — January 26, 2010

Buy Kamagra Earn Google M65 Jacket Viagra Cialis Cheap Kamagra Cheap Viagra Cheap Cialis Make Money on Google M65 Field Jacket Airline Dog Carrier Airline Dog Carriers Viagra Cialis Earn Google Airline Dog Carrier Airline Dog Carriers Airline Approved Dog Carriers ED Hardy Wholesale Copy DVD Software How to Send Fax 14k Yellow Gold Redneck Costume 14k Gold Heart Tandem Baby Stroller

Comment by kamagra — January 29, 2010

Leave a comment

You must be logged in to post a comment.