JavaScript is a great language with a few bad parts. For all its expressiveness and power, JavaScript can at times be awkward, visually noisy, and downright painful. And although none of these problems are fatal, it sure would be nice if there was a way not to deal with them.

Well, maybe there is.

Meet CoffeeScript. Created by Jeremy Ashkenas, this relatively new language provides syntactic sugar on top of JavaScript. It looks a lot cleaner, gives you more bells and whistles, and eliminates some of JavaScript’s more painful gotchas. Most importantly, it compiles into JavaScript Lint-compatible JavaScript. Very nice!

CoffeeScript seems to be really picking up steam lately. It’s finally getting good tooling support (more on that later), industry acceptance (see great posts on it from Elegant Code’s Jan Van Ryswyck and Microsoft’s Scott Hanselman), and just overall buzz.

Naturally, I had to jump on the bandwagon.

I’m Intrigued, Tell Me More

CoffeeScript gives you a whole bunch of niceties, but a few really stand out:

Function Syntax. There is no question that JavaScript starts and ends with functions. They’re first class citizens within the language and can do pretty much everything an object can. Not only that, functions are how you do encapsulation.

Yet the syntax around functions can definitely get funky. It’s visually noisy and at times odd. CoffeeScript really cleans this up. For instance, say you wanted to write a function to get the Ultimate Answer. In JavaScript, you would probably do something like this:

ultimateAnswer = function() {
    var answer;
    return answer = 6 * 7;
  }

In CoffeeScript, this function would be written as:

ultimateAnswer =>
   answer = 6 * 7

What changed? Well, the keyword function turned into ->, curly braces and semicolons disappeared, and the return value was omitted. At first blush, these are all nice improvements, but nothing really earth shattering. Is there more to it?

Yes there is. Things get a little more interesting when CoffeeScript actually compiles this code into JavaScript:

(function() {
  var ultimateAnswer;
  ultimateAnswer = function() {
    var answer;
    return answer = 6 * 7;
  };
}).call(this);

A few things to note here. First, the whole thing is wrapped in a global function which is then immediately executed. Second, CoffeeScript automatically returns a value from your functions whenever possible. And third, your variables are properly var‘ed without you having to worry about it.

What these compiler niceties get you is safer and more robust JavaScript.

There’s other function goodness as well: easy syntax for self-executing functions, parameter defaults, function binding, etc. For more on this, see excellent posts from Jan Van Ryswyck here and here.

Scoping. Scope is probably one of JavaScript’s weakest points. There is no block scope and globals are very easy to bleed into the code (just omit the var keyword and watch the fireworks). CoffeeScript deals with this by automatically hoisting up variable declarations, making var unnecessary (and actually illegal to use), and wrapping your entire program in a global, self-executing function.

Here’s an example from the CoffeeScript site:

CoffeeScript JavaScript
outer = 1
changeNumbers = >
  inner = -1
  outer = 10
inner = changeNumbers()
(function() {
  var changeNumbers, inner, outer;
  outer = 1;
  changeNumbers = function() {
    var inner;
    inner = -1;
    return outer = 10;
  };
  inner = changeNumbers();
}).call(this);

The impact of such medicinal product has been available in 5mg, 10mg & 20mg sachets which the patients can purchase from the drugstores & they are also available on the online drugstores at affordable rates. free samples cialis It will boost your size and super cialis professional erection. It contains the Sildenafil citrate produced through different technology that shows effect in women. on line levitra The new jelly by Ajanta Pharma, which is kamagra jelly, becomes effective in just 15 minutes. http://djpaulkom.tv/photos-throwback-thursday-featuring-dj-pauls-long-hair-and-hypnotize-minds-car/ levitra 20 mg
The outer variable is automatically declared at the top, which prevents the inner function from re-declaring it.

Classes. Ok, so JavaScript doesn’t have classes, even though it sort of looks like it does. CoffeeScript on the other hand does have classes. Again, from their site:

class Animal
  constructor: (@name) >
    move: (meters) >
    alert @name + " moved #{meters}m."

class Snake extends Animal
  move: >
    alert "Slithering..."
    super 5

class Horse extends Animal
  move: >
    alert "Galloping..."
    super 45

sam = new Snake "Sammy the Python"
tom = new Horse "Tommy the Palomino"
sam.move()
tom.move()

Quite a bit of functionality is available here. Classes can be defined, initialized, and inherited from. Derived types can call parent functions. Good stuff.

A notable omission in CoffeeScript is support for private methods. In spite of multiple discussions, CoffeeScript maintainers ultimately decided against implementing the syntax to explicitly support method hiding because JavaScript itself doesn’t really support it.

So, depending on what you’re looking to do, you could either use the traditional encapsulate-through-closures approach or just use the convention of prefixing private methods with an “_”. There is a good discussion here on this topic.

This is Great, Where do I Sign up?

Assuming you’re sold on the concept, how would your team adopt CoffeeScript? Well, it would be nice to have your IDE support it (for syntax highlighting and such). Some including NetBeans, IDEA, and Cloud9IDE already do and support for Visual Studio is in the works.

It would also be nice if working with CoffeeScript was seamlessly integrated into developer workflow. To that end, there is a nice NuGet package called CoffeeSharp you should consider. This package can compile your .coffee files, either on demand or as a pre-build step.

Update: Mindscape just recently released a free plugin for Visual Studio called Web Workbench which, among other things, adds syntax highlighting and JavaScript compilation to CoffeeScript files.

And What About My Old JavaScript?

Another thing to consider is existing code. After all, if you’re thinking about using CoffeeScript, there is a good chance that you already have a bunch of JavaScript created. One option is to let sleeping dogs lie and leave the legacy stuff alone.

Another, funner option is to pull the old switcheroo and convert that JavaScript into CoffeeScript. There are converters out there: http://ricostacruz.com/js2coffee/ or https://github.com/mindynamics/js2cs. How well they work is debatable, but they will probably get you most of the way there.

P.S. Jeremy Ashkenas gave a great presentation at JSConf 2011 about CoffeeScript (his part starts at the 19:50 mark). Aside from a discussion on CoffeeScript philosophy and syntax, he also shares insights on what it took to create the language (stuff like lexing, parsing, etc). Very cool.

You may also like:

Did you love / hate / were unmoved by this post?
Then show your support / disgust / indifference by following me on Twitter!

Comments are closed.