Switching to CoffeeScript


JavaScript feels like Stink Spirit, the character in Miyazaki’s Spirited Away, who one day arrives at a bathhouse, loaded with all the filth it accumulated through the years. In the movie, Chihiro's, through her courage and generosity, helps Stink Spirit cleanse, and while its essence is unchanged, it comes out cleaner, purer… which brings me to CoffeeScript.
A few months ago, at Orbeon, we started using CoffeeScript instead of JavaScript for our client-side code. Just as when we started using Scala instead of Java for server-side code, the switch wasn't disruptive: CoffeeScript compiles to readable JavaScript, and so we could start using CoffeeScript for new functionality, while leaving existing code in JavaScript. So far, our experience has been all but positive. CoffeeScript will help you to:
  • Get rid of the cruft — This isn't only about using less characters; more importantly it is about making what is important stand out. Case in point: comprehensions.
  • Avoid common errors — this is a source of numerous mistakes, as it works differently than its counterpart in Java. Certainly, your JavaScript code is bug free, but even so: making sure this is bound to the object you intend it to be is a constant preoccupation, and creates more complicated APIs. Depending on the cases, I've resorted to declaring a var self = this, to Underscore's bind as in addListener(_.bind(function() { … }, this), or to creating APIs with additional parameters as is often the case in YUI. CoffeeScript's fat arrow elegantly solves this.
  • Using object oriented programming — I always loved functional programming, but there are case where classes are the right tool for the job. JavaScript discourages this approach by making it overly complicated. In contract, CoffeeScript gives you a simple and clear way to declare classes.
Those are just a few examples, and the whole is greater than it parts: you are left with a language that feels fresh, attracts rather than repulse, and I'm looking forward to write new functionality and refactor some of our existing client-side code using CoffeeScript.