April 18, 2012 - No Comments!

CoffeeScript Makes JavaScript Go Down Smooth

CoffeeScript is a great little language that compiles down to readable, clean JavaScript. When we were recently in Costa Rica I gave a lightning talk on some of CoffeeScript's cooler features. It's great on the surface, since this:

$("#foo").click(function () {
bar( "some text #{ something / 2 } a unit" );

is more cleanly written as this:

$("#foo").click ->
bar("some text " + something / 2 + "a unit" )

But as I've been writing more JavaScript, there are a handful of other neat things I find myself using a lot. Here are a few:



This is a little one, but the switch statement in CoffeeScript is just so nice it's one of the first things I go to when rewriting old JavaScript. Not only can you rewrite:

if (foo === bar) {
value = thing_one();
} elsif (foo === baz) {
value = another_thing();
} else {
value = somthing_else()

as the somewhat terser:

switch foo
when bar then value = thing_one()
when baz then value = another_thing()
else value = somthing_else()

but, since everything is an expression in CoffeeScript, you can just make that:

 value = switch foo
when bar then one_thing()
when baz then another_thing()
else something_else()

The Fat Arrow

The fat arrow (=>) also cleans up a lot. When you use it in an object, that function will be bound to the scope of its caller, which means that you can do something like:

$("p").click ->
    setTimeout (=>
), 10000


Where CoffeeScript really shines is when you start making new classes. I've found myself shying away from OO in JavaScript before, because it's kind of unusual and has a lot of pitfalls. CoffeeScript makes JavaScript's object and inheritance system useable and fun.

Take this highly contrived example:

class Person
act: (name, action) ->
class Child extends Person
act: (name, action) ->
if name == "Drink" and @is_good # the same as this.is_good
alert "No thanks"
super name, action
f = new Child
f.is_good = false
f.act "Drink", ->
alert "glug glug glug"

The class and super keywords make this so painless, you have no excuse not to write pretty Object Oriented JS in all your projects.

There is tons more to see at Coffeescript.org. What you'll find, as you start rewriting code into CoffeeScript, is that it really makes the cool parts of JavaScript pop out. If you still haven't gotten your fill, you can check out underscore.js and backbone.js, both, like CoffeeScript, by the incredibly talented and prolific Jeremy Ashkenas.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.