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
when compiled to CSS, produces
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:
So, why the question mark in the title?
This 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 :)