Ode to Coffeescript

(this started as email to a friend but I thought it might be useful to share)

I’ve been using coffeescript for about a year. Other than using it for my own projects, I have learned it's syntax from the coffeescript website and from the random coffeescript snippet that I see here and there.

I started using it to try and write expressive code that reminded me of Ruby. I like my code readable, with very descriptive (and sometimes long) variable names (never abbreviated) and few comments. If I can’t understand the code by reading it, then I probably need to split up my one-liner into a few lines or make a new function or two.

Being able to abandon a lot of the extra braces and parens for indentation helped for readability (I actually agree with Python over Ruby on this one), especially relative to the javascript that I was writing before.

Initially I used all of the looping shortcuts that coffeescript comes with, but now I tend to use underscore.js whenever I am looping/mapping/etc. I am not sure if this is what @jashkenas had in mind (did this guy really write coffeescript, underscore and backbone??) but I think coffeescript + underscore results in a really nice compromise.

I have only recently really understood that everything is an expression in coffeescript. Using it really helps me to modularize my code

Here’s an example I have just written that sort of sums up what I like about coffeescript:

Line 1. Takes advantage of "everything is an expression". Whatever the block indented below line 1 returns, will be set to formElement. This is so much better than initializing an empty string and then setting it.

Line 2. Note that I am using underscore to check if the value I am interested in is in an array. If so, then line 3 just returns the screen which bubble back to line 1. Same thing with line 4-5.

Line 7. See how we can do ruby style string interpolation. That is huge - so huge. Javascript doesn't let you do sane multi-line strings, nor can you interpolate. But wait - check out the crazy interpolation of line 8 - I start a multi-line map (underscore again!). Coffeescript basically enables quick and dirty templating inside any string. It's a bit dangerous to mix too much logic and templating, but for small things it is awesome. (I use handlebars.js for the big jobs)

Anyways, it's not the greatest code in the world, but it's real code I wrote yesterday and it's helping me get the job done.

I am one of those people that think you should learn a new programming language every year or so – and indeed coffeescript has made me a better programmer. So if you are learning it, I recommend that you stick with it. You’ll get it and be better for it.

0 Response to Ode to Coffeescript

Post a Comment