By eidias on (tags: coffeescript, javascript, categories: tools, web)

There’s been a lot of fuss about coffee script in the last few months. It’s a language that compiles into pure javascript. Some people like it, some don’t. So what’s it all about?

Javascript causes vigorous discussions. It’s a very specific language – it has it’s flaws but has it’s strengths as well, but most importantly, it allows you to do a lot of things generally considered as weird or dangerous by most programmers. If you look at that fact from a different perspective – it gives you awesome power – but it’s up to you if it’ll explode in your face, or serve it’s purpose. One thing is for sure – you need to be quite the expert to utilize it’s capabilities and not burn yourself along the way – I’m still struggling to get to that point.

Why the lengthy intro? Coffee script was developed so that you won’t run into the perils of javascript. It introduces a new syntax, protects the programmer from various dangers (like global scope polluting) and in assumption – improves code readability.

The syntax is definitely something that one needs to get used to. Some structures resemble python, some ruby (from what I read), but overall it looks nice and clean. Here are a couple of my favourite features:

  • “This string will be filled with #{variable} value” – string interpolation - yes, in this case “variable” is a variable name
  • foo = (first, others…) – they’re called “splats” and allow to define functions with variable parameter number
  • eat food for food in ['toast', 'cheese', 'wine'] – python like comprehensions – these are awesome
  • start = numbers[0..2] – again python like, this time array slicing and splicing
  • footprints = yeti ? "bear" – existential operator (like ?? in c# except this checks if variable is null or ‘undefined’)
  • [city, temp, forecast] = weatherReport "Berkeley, CA" – deconstructing assignment – again python like return ‘capabilities’

Here is the language reference.

Now, to use this, there are a couple of ways. One is to use it during build using an executable. This way does not look like something comfortable to use during development though. The other, is to use a javascript file and compile coffee script on the client – well, that’s a no go for me for political reasons. The third is to use the new mvc 4 bundling feature – just like with less – and that would be my choice.

This definitely looks like something worth trying out in real project.