CoffeeScript: A Love Story?

I’m currently going through the same phase in my relationship with CoffeeScript that I went through a year ago with Haml and Sass. For those of you unfamiliar with CoffeeScript, its just a little syntax language that compiles directly to Javascript. Why would you want that? Well, let’s look at Haml and Sass:

Haml

Haml code looks like this:

#wrapper

  #sidebar

    %a{:href => 'http://google.com'} Google

  #content

    %img{:src => 'lolcats.jpg'}

which when compiled to HTML, produces

The cool part here is that since Haml is auto-closing all of your tags, they’re automatically balanced. And the syntax is easier to read (IMO).

Sass

$padding_size: 20px

#sidebar a, a:visited

padding: $padding_size / 2

text-decoration: none

when compiled to CSS, produces

#sidebar {

padding: 10px;

}

#sidebar a, #sidebar a:visited {

text-decoration: none;

}

So Sass uses the benefit of precompilation to add a few features (and mixins) to CSS. Above we can see in use: (1) variables, (2) math, (3) nesting.

CoffeeScript

So then there’s CoffeeScript. If you haven’t tried the “Try CoffeeScript” demo yet, totally do that. Since the CoffeeScript compiler is implemented in JavaScript it can run for reals right in your browser. When you’re ready to use it, if you’re using Rails,Barista is pretty awesome and quick to set up.

So now – why CoffeeScript again? CoffeeScript addresses a major pain point for Javascript developers: appearance, and JSLint. CoffeeScript always compiles to code that is set for JSLint (and normally more performant).

So this code in CoffeeScript:

square = (x) -> x*x

numbers = [2, 3, 4, 5, 6]

numbers.each (x) -> square(x)

Compiles to:

var numbers, square;

square = (function(x) {

return x * x;

});

numbers = [2, 3, 4, 5, 6];

numbers.forEach(function(x) {

return square(x);

});

So, why the question mark in the title?

This doesn’t doesn’t speak well to Haml, but Sass makes changing CSS much, much easier. CoffeeScript changes Javascript syntax to make it more likable, but its still just Javascript. We probably shouldn’t be adding entire steps to our process just to make things prettier and lint-free, but on the other hand – its so nice :)

Tags: , , , ,

  • Pingback: Writing Node.js in CoffeeScript - See John Code

  • http://dandascalescu.com/ Dan Dascalescu

    The JavaScript output for square should be:

    square = function(x) {
    return x * x;
    };

    • http://seejohncode.com/ John Crepezzi

      Hmm – if there was an equal sign on the first line that would be true (this output is directly from the coffeescript compiler). Anyway, there was meant to be one in the coffeescript, so I’ll update the example – thanks!