How Coffeescript can make your life easier

By | June 30, 2012

As any developer that has to build web applications you will love and hate JavaScript. It provides you with a powerful way to build an application online. But the code can easily become extremely chaotic, long, complicated and unreadable. And these things are a developers worst nightmare. This is were Coffeescript comes in.

The developers of Coffeescript describe it best with:

Underneath all those awkward braces and semicolons, JavaScript has always had a gorgeous object model at its heart. CoffeeScript is an attempt to expose the good parts of JavaScript in a simple way.

Coffeescript offers a way to make JavaScript code better to read and maintain. It does this by introducing a new syntax style to structure existing JavaScript code. It does this by reducing clutter of brackets and creating a more human readable language.

I’ll give a simple example demonstrating how Coffeescript can make you’re code better readable. Where we used to have to write huge amounts of code for simple things, like:

function test() {
  var data;
  var my_class = {
     init: function(my_data) {
         data = my_data;
         this.doStuff();
     },
     doStuff() {
         alert('Stuff is done');
     }
  };
  return my_class;
}

With Coffeescript you can reduce this to a few simple lines:

test = ->
   init: (my_data) ->
     @data = my_data
     @doStuff()
   doStuff : ->
      alert 'Stuff is done'

As this simple example shows Coffeescript not only reduces the number lines of code, but it also removes the overly complicated and unreadable brackets as well as introducing more context aware code. The CoffeeScript compiler will translate that code to some actual JavaScript that the browser can understand. So how does all off this magic work you might be wondering.

Well Coffeescript eliminates the use of brackets by parsing a tab as if it is a code block. So all code with the same indentation level will be in a set of brackets. Keep in mind that your source files will have to be TAB oriented to achieve this.

Using Coffeescript will require you as developer to install a few extra tools into your editor of choice. Being the Coffeescript compiler plug-in. This will convert the *.coffee files into regular *.js files.

Leave a Reply