Write a lot of JavaScript? Love clean code? Then you need to check out CoffeeScript, a nifty little languages that compiles into JavaScript. Why would you want to learn some new language and spend time compiling? Because, in exchange, you get some of the best syntactic features from Ruby, Groovy and Python and your code becomes more readable, concise, DRY and easier to maintain.
One of my first experiences with CoffeeScript was writing a simple OAuth client and Connect Middleware for a node.js app that would allow me to authenticate with the LinkedIn API’s. As I worked on this, I took note of some of my favorite features of CoffeeScript:
Defining classes and inheritance
The syntax for defining classes in JavaScript can be unintuitive, especially for those of us coming from a Java or C++ background. Actually, to be more accurate, JavaScript uses prototypal inheritance, so there really are no classes. This in and of itself isn’t a bad thing, but JavaScript’s syntax for specifying what an object does and where it inherits behavior from is clunky and awkward. For example, here is the “standard” way to define my LinkedInClient class:
The syntax gets even weirder if I wanted LinkedInClient to inherit from BaseClient and delegate some of the work to it:
CoffeeScript’s solution isn’t to avoid prototypal inheritance but instead to provide some very clean and readable syntax around it:
The class, extends and super keywords all translate into normal JavaScript prototypal inheritance constructs, but they are far more concise and readable.
Defining functions
JavaScript is a functional language, so defining functions is a very common activity. Here is a side-by-side of JavaScript and CoffeeScript function declaration:
CoffeeScript saves you some typing be making function declarations consist solely of an optional list of parameters in parenthesis followed by an arrow. Moreover, CoffeeScript doesn’t use semi-colons or curly braces; instead, indentation is used to specify blocks. Although meaningful whitespace can occasionally lead to some strange errors, it does allow for a more compact and uniform code style.
This keyword
CoffeeScript has a few nice features related to the this keyword. First, CoffeeScript uses the @ symbol as shorthand for this.. For example, @foo is equivalent to this.foo. Second, if you use the @ symbol in the parameters of a function, CoffeeScript will automatically assign those values as properties of the object. For example, the following two snippets are equivalent:
Finally, most JavaScript programmers will, at one time or another, run into an issue where this isn’t quite what they thought it was. The this keyword in JavaScript is dynamically scoped and changes meaning depending on how the function is called. For example, if you use a function as a callback handler for a click event, the this keyword will be different when the callback is executed:
(If you find this confusing, head over to the JavaScript Garden and read up on the this keyword.) The typical workaround is to save a reference to this in another variable:
CoffeeScript has a far more elegant solution for this common gotcha: use the ‘fat arrow’ => instead of the ‘thin’ arrow -> when defining your function and the this keyword will be bound for you on the spot:
String interpolation
Here’s a simple one: you need to construct a string that includes some variables. In JavaScript, the code looks like this:
CoffeeScript supports interpolated values within a string using the #{..} syntax:
Existential Operator
Consider the following snippet of JavaScript:
There are a number of ways this code could throw an exception: model could be null or undefined; the profile property might not exist, or it might not be a function, or it might return null; location could be null; and so on. The “defensive coding” version of that snippet might look like this:
CoffeeScript’s existential ? operator is shorthand for a “not undefined and not null” check, which cuts the previous snippet down significantly:
Further reading
CoffeeScript has many other features not discussed in this post: comprehensions, destructuring assignment, lexical and variable safety, default function parameters, and a whole lot more. I encourage you to checkout the CoffeeScript homepage, A CofeeScript Intervention, 10 CoffeeScript One Liners to Impress Your Friends, and CoffeeScript Tricks. To support rapid iteration/experimentation, I highly recommend running the CoffeeScript compiler with the “watch” (-w) flag so that it recompiles your coffee source files every time you hit save.
Clean code
As a software engineer, your job is to solve problems (1) correctly, (2) efficiently, and (3) cleanly. CoffeeScript is all about #3. It makes it easier to write code that clearly communicates its intent; code that is concise and DRY; code that, when you come back to it 6 months later, is not a total nightmare to understand. Give it a try and see if it doesn’t make JavaScript coding just a bit more fun for you.