The developer’s toolkit: CoffeeScript

June 14, 2012
By

There’s no denying it: the world of JavaScript is exploding right now. If you follow the web dev community on Twitter, Hacker News, etc., not a day goes by that you don’t hear about a new JavaScript library seeking to buttress the already-massive JS arsenal.

A few weeks ago, I talked a bit about the wonderful raphael.js, but I’ve since come across a great deal more, some of them intended to add lots of baseline functionality to JavaScript (like Underscore) and others filling more specific niches, like Gmaps.js, which I’ll cover next week.

But there’s yet another reason why it’s a wonderful time to be working with JavaScript: CoffeeScript. CoffeeScript has the syntactical simplicity of other languages like Ruby and Python, but it compiles directly into JavaScript. The similarity to Python is probably the most pronounced, as CoffeeScript relies on significant whitespace, which is one of Python’s enduring hallmarks (though CoffeeScript’s use of whitespace, much like Python’s, has inspired dissent in some quarters).

I became interested in CoffeeScript through one of our senior developers, Matthew Lyon. Matthew is not especially prone to hyperbole, and so his description of CoffeeScript as his current candidate for a syntactically “perfect language” in a casual conversation is one that I took very seriously (Matthew has also been quite active in the CoffeeScript community for some time).

I was not disappointed when I had a look myself. The official documentation for CoffeeScript is already excellent, but I’ll give a brief intro of my own here.

Getting Started

The first thing I liked about CoffeeScript is that the actual act of compiling JavaScript from CoffeeScript is incredibly easy. Upon installing, compiling test.coffee into CoffeeScript is a single command in the CLI:

coffee -c test.coffee

Here, -c just means “compile.” When you run this command, a test.js will pop up in the same directory. This enables .coffee and .js files to mingle in the same directory and rely on one other quite comfortably.

Language Mechanics

As far as the mechanics of the language itself go, CoffeeScript is actually vastly different from JavaScript in crucial respects. First of all, the word “function” can be removed entirely when using CoffeeScript. Here’s a basic function “add” that will add integers a and b together:

add(a,b) ->
    a + b

The resulting JavaScript:

add(a, b)(function() {
    return a + b;
    });

(Notice that there are no semicolons, which have produced more than a little vitriol from all sides over the years. Fortunately, semicolons play no role whatsoever in CoffeeScript.)

Here is how you would define an object “car” with the methods “honk,” “drive,” and “stop:”

car =
honk:
drive:
stop:

The compiled JavaScript looks comes out like this:

var car = {
honk: … ,
drive: … ,
stop: …
};

It’s borderline amusing that providing as little as -> in CoffeeScript gives you an empty anonymous function in JavaScript:

(function( ){ };)

There’s even a console on the official site that enables you to watch the conversion happen on the fly (just hit the “Try CoffeeScript” tab at the top).

Classes, Finally

But these basic examples are really just the tip of the iceberg. What has impressed me most about CoffeeScript thus far is its ability to allow you to quite easily deal with classes instead of JavaScript’s more native system of prototyping. JavaScript wasn’t originally intended to enable you to use classes the way that languages like Ruby and Python do, which allow you to declare classes and then manufacture independent instances of that class. You can do something for all intents and purposes like this in JavaScript, but the result is extremely difficult to implement in practice (as we will see below).

CoffeeScript, on the other hand, makes working with classes a breeze. The class Car can be declared as class Car, and can be extended from the class Vehicle like so:

class Car extends Vehicle

in CoffeeScript compiles into the following unwieldy JavaScript:

var Car,
  __hasProp = {}.hasOwnProperty,
  __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

Car = (function(_super) {

  __extends(Car, _super);

  function Car() {
    return Car.__super__.constructor.apply(this, arguments);
  }

  return Car;

})(Vehicle);

Just to be clear, this is not “better” or “worse” than JavaScript, and arguments for and against CoffeeScript need not be made on that basis. What CoffeeScript does do is enable programmers steeped in object-oriented programming to more readily employ class-related abstractions in JavaScript. This might be something you find necessary and appealing. Or not. It will all depend on how you use JavaScript and what you demand from it.

There are cases where it strikes me as being quite useful. Let’s say that you’re working with node.js and are doing JavaScript all the way down, so to speak, in your web app, and would like to work with an MVC-style structure, but to build everything up on your own, without relying on one of the many MVC-style frameworks written for node. Using out-of-the-package JavaScript, this would be quite difficult, and would make the transition quite difficult for someone with a background in Rails, for example. It’s no accident, in fact, that some full-stack node frameworks like Tower.js rely heavily on CoffeeScript for the “M” in “MVC.”

If you’re developing in a way that relies heavily on complex data models, then class constructors–as well as class extension, hierarchization, etc.–are absolutely crucial. I would even venture to guess that clean specification of class hierarchies and dependencies in JavaScript will become increasingly important as more and more model- and persistence-related functionality is demanded of JavaScript over time (libraries like Backbone and Knockout being prime examples).

If JavaScript has given you trouble in the past, whether due to its syntax or something else, then CoffeeScript might just be right up your alley. And if you’re already a JavaScript pro or close to it, I would implore you to experiment with the console and see if there could indeed be significant benefits associated with either switching completely or using CoffeeScript for a carefully defined set of use cases.

Tags:

Read from Source

PaasMag

Paasmag Logo

Twitter

Paasmag Twitter

Tweets