Tuesday, April 17, 2012

When to use CoffeeScript?

Plenty of us are writing applications in Javascript, whether we are writing mobile app code, getting the most of node.js, or just building a website. The CoffeeScript invention came out a few years ago and it really looks great with its promise to make app programming easier.

But we still have to learn Javascript, or at least the good parts, including some things like its functional programming syntax which can get hard to read and oh yeah you have to use === instead of == in a number of cases. CoffeeScript makes these things much easier but if we have to start debugging or using other people's libraries we still have to deal with some of these quirks in Javascript.

And for some rapid development tasks, we can question if it is even worth adding the extra compile step to start using CoffeeScript.

I believe it is worth adding the extra steps to start using CoffeeScript if there are multiple modules or any form of OOP or functional programming are needed. I spent 1-2 months building a mobile application for a client using Javascript modules until I started working on a Cordova/PhoneGap plugin written in CoffeeScript. I started making some changes to its API and really found the CoffeeScript so much easier to manage and refactor. I was able to use js2coffee to convert most of my modules to CoffeeScript and it is so much easier to make the changes and refactor into smaller modules.

This morning I needed a web server that calls a JSON API and returns a certain part of the results. In node.js, there are a couple of levels of callbacks that are needed to handle the asynchronous nature on all sides. I thought about doing it in Javascript and realized that the complexity of handling the callbacks and functional programming can really blow up and it will be much smoother in CoffeeScript. I wrote about how to do the JSON services in node.js here.

The only time I see not to use CoffeeScript is in a community where other people are still using Javascript. I have worked on a Cordova/PhoneGap SQL API and other people have been helping to make some improvements in the Javascript version. In this case, I still want to keep the CoffeeScript version to make refactoring easier but will have to make the Javascript version leading.