New technology of the week, and hot contender for the title of ‘my current favourite language’, is coffeescript.

I’ve thought for a long time that javascript is a horrible language with a wonderful language inside trying to get out.   Coffeescript may well be that language.  While at it’s heart it is still fundamentally javascript, and can be used anywhere javascript can (so far I’ve used it in node.js and in the browser), it steers you around the worst mistakes of the underlying language.  Variable scoping and binding is handled better, function declarations are clearer, iterations and comprehensions are integrated neatly into the language, and your code can be more succinct.

This week I re-wrote our mobile web platform, replacing our existing jquery-ui based rendering with coffeescript and backbone.  There was definitely a learning curve involved, but the effort was worthwhile; and now we have a code base that is considerably more manageable than the previous version.

Examples

l=[1,2,3]
square = (x) -> x*x
squares = (square(x) for x in l)

Or even

squares = (x*x for x in [1,2,3])

And from our actual code: we store data as json-encoded strings in the browser’s local storage.  This function takes a predicate (i.e. any function that returns a boolean) and uses it to find the keys of all elements in local storage that match.

view : (predicate) ->
    (key for own key,value of localStorage when predicate (JSON.parse(value))

Which could then be used to get all objects that have a field ‘type’ set to ‘response’ as follows:

dockeys = view (doc) -> doc.type=='response'

Neat, huh?   Head over to http://jashkenas.github.com/coffee-script/ and try it out yourself!