CoffeeScript anyone?

Tomasz Agurkiewicz

What is CoffeeScript? It’s a little language that compiles into JavaScript. And it’s so much simpler to write and look at than original Javascript. And the best part of it? Underneath it all it is still pure JavaScript!

I have to admit I was a bit sceptical at first. After looking at the documentation the syntax looked funky, and I thought that I would have to install a compiler, then run it every time I want to have a working JavaScript. It seemed like a lot of trouble. But guess what – it’s not!

The only thing you need to get started using CoffeeScript with Visual Studio is Mindscape Web Workbench. Install it, restart VS and you’re ready to go. Just add a new CoffeeScript file to the solution and on each save it automatically compiles to JavaScript – so at all times you have an up to date JS file ready for use in your web application.

So what is the strength of CoffeeScript? Its syntax and its flexibility. You can use CoffeeScript syntax, which for me feels a bit like Visual Basic, but you can write your usual JavaScript if you feel like it. CoffeeScript tries to remove the need to type boilerplate code as much as possible. No more ‘var’, no more ‘function’, no more ‘;’ or curly brackets – you only type the meaningful stuff.

class A
 method: (arg) ->
  alert arg

x = new A()
x.method "text"

Translates into:

var A, x;
A = (function() {
  function A() {}
  A.prototype.method = function(arg) {
    return alert(arg);
  };
  return A;
})();
x = new A();
x.method("text");

“The compiled output is readable and pretty-printed, passes through JavaScript Lint without warnings, will work in every JavaScript implementation, and tends to run as fast or faster than the equivalent handwritten JavaScript.”

And if you feel like x.method “text” just doesn’t seem right you can still write x.method(“text”) in CoffeeScript and will work just fine.

Head on to http://jashkenas.github.com/coffee-script/ to learn more about it. And I dare you to go to the “Try CoffeeScript” tab and add a simple “class B extends A” to my code and observe what CoffeeScript does for you.

Writing in CoffeeScript is easy once you get used to it. Although it’s hard to use functions without brackets and ‘function’ definition at first and it seems odd but after an hour or so you get used to it. And what is most important – it saves you a lot of writing. A quick look at my code shows that a 100 lines of very readable code in CoffeeScript translates into roughly 200 lines of Javascript.

And for desert, my favourite example:

eat food for food in ['toast', 'cheese', 'wine']

Translates into:

var food, _i, _len, _ref;
_ref = ['toast', 'cheese', 'wine'];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
  food = _ref[_i];
  eat(food);
}

I’m sticking with CoffeScript.