Why should you use CoffeeScript instead of JavaScript?

Date:
Tags:
Tutorial CoffeeScript Development
By

CoffeeScript is currently my favourite language to write in! That is because CoffeeScript contains three things that I like in a language:

  1. easy function and lambda definitions
  2. syntactically significant whitespace
  3. straight forward class definitions

However, for all its benefits, CoffeeScript is complicated by its intertwined relationship with Javascript. This is because CoffeeScript is a language that doesn't compile to binary or VM code, but it is transpiled to Javascript. So, to understand why you should use CoffeeScript you should probably understand why you should use it instead of Javascript.

In this post I will go over how to get started with CoffeeScript, and give a few useful examples where it is a great improvement over JavaScript. This is not a complete tutorial of CoffeeScript, it is more a primer to get you excited to learn it.

Note: to parse this document a basic level of JavaScript is needed. If you are unfamilar with CoffeeScript perhaps you could try The Little Book on CoffeeScript

#History

Underneath that awkward Java-esque patina, JavaScript has always had a gorgeous heart. CoffeeScript is an attempt to expose the good parts of JavaScript in a simple way. -- coffeescript.org

CoffeeScript was created by Jeremy Ashkenas (creator of underscore.js and backbone.js) in 2009, to make Javascript simpler and more readable. It takes elements from Ruby, Python and Haskell to create its blend of functional and OO features.

It has seen a massive uptake in the community, in part because of its inclusion in Ruby on Rails since version 3.1. It has also had upstream affects on Javascript, where Brendan Eich (creator of Javascript) has proposed CoffeeScript-like changes for future JavaScript versions (here).

#Philosophy

The golden rule of CoffeeScript is: "It's just JavaScript" -- coffeescript.org

CoffeeScript is just a prettier JavaScript. It will let you have smaller and more readable code by taking core elements of JavaScript and giving you a better way of writing it.

The main reason why some people dislike CoffeeScript is they don't want to write in CoffeeScript and debug in JavaScript. CoffeeScript trys to be nicer JavaScript, and to keep the output code similar to the input so that debugging is trivial. Personally, I have never found this a hurdle to debugging, and I don't think you will either.

#Getting Started One reason why JavaScript is so popular is the ease in which anyone can access it. In that vein, I will get you up and running with CoffeeScript ASAP. You can quickly start using CoffeeScript by either:

  1. Going to http://coffeescript.org/ and clicking Try CoffeeScript at the top.
  2. Include CoffeeScript in an HTML page with <script src="https://rawgithub.com/jashkenas/coffee-script/master/extras/coffee-script.js"></script> in the <head> then wrap code in <script type="text/coffeescript"></script> tags.
  3. Install the CoffeeScript console with Node.js and npm with npm -g install coffee-script then run it with coffee.

Note: These are not ways to use CoffeeScript in production, they are tools for learning and testing CoffeeScript.

#Syntax I will go over the CoffeeScript syntax in the order of my favourite parts; functions, whitespace, classes.

##Functions

Lets start with functions in CoffeeScript:

times_two = (x) -> x*2

Read this as

  • times_two equals
  • a function that takes an input (x)
  • moves it to (->)
  • output of x*2

I think this is the most beautiful function definition syntax that exists. It uses syntax similar to Haskell's function description Integer -> Integer, and Ruby's implicit return of the last statement.

This CoffeeScript will compile to the JavaScript:

``` var times_two;

times_two = function(x) { return x * 2; }; ```

First JavaScript has to define a variable, because of the worst gotcha in programming, default global scope! Then it uses the long function keyword to define a function, wrapping the code in { and }. The function then explicitly define the returned value with return.

I think this JavaScript is ugly, it has lots of code junk (like chart junk), i.e. unnecessary elements not required to convey the functions purpose. However, it clearly maps to the CoffeeScript. The variable names are the same, and although more verbose, the function definition is the same. This is due to CoffeeScript's philosophy to output readable JavaScript.

There are a few more benefits of CoffeeScript functions, like the optional parenthesis and argument definitions, e.g. this code:

log = -> console.log arguments

will compile to the JavaScript:

``` var log;

log = function() { return console.log(arguments); }; ```

There are many things to learn with CoffeeScript functions, the closure creating do keyword, default values in constructors, the fat arrow, they are icing on the Coffee cake.

##Whitespace Similar to Python, CoffeeScript uses syntactically significant whitespace to group blocks of code. For example:

fn = (x) -> x += 2 x *= 4

Most people will indent their code to give an immediate visual clue as to its organisation. CoffeeScript takes this convention and makes it part of the language to tidy up all those curly braces.

Indentation works for any statement that requires a block, like if and for statements:

for num in [1..10] if num % 2 == 0 console.log "#{num} is even" else console.log "#{num} is odd"

will compile to the JavaScript:

``` var num, _i;

for (num = i = 1; _i <= 10; num = ++i) { if (num % 2 === 0) { console.log("" + num + " is even"); } else { console.log("" + num + " is odd"); } } ```

Indentation adds to the readability of CoffeeScript and it removes lots of the unnecessary braces.

##Class Definitions It seems silly, when put into the context of other programming languages, that a common question in JavaScript is 'What's the best way to define a class in JavaScript?'.

When asking how to define a class in any other language, would it (as the StackOverflow mod put it) 'likely solicit debate, arguments, polling, or extended discussion'? I would say NO. Most languages have a clear way to define classes, e.g. Ruby's, Java's, C#'s, PHP's ... it is the class keyword.

JavaScript is a language limited by few rules and its ability to define OOP-ish classes in many ways is powerful, yet confusing to many. CoffeeScript solves this by adding the class keyword:

``` class Person constructor: (@name) ->

hello: -> console.log "Hello #{@name}" ```

Note: @ is short for this., and (@name) -> is short for (name) -> @name = name.

This compiles to the ugly JavaScript:

``` var Person;

Person = (function() { function Person(name) { this.name = name; }

Person.prototype.hello = function() { return console.log("Hello " + this.name); };

return Person;

})(); ```

This JavaScript code is not as straight forward or trivial as the CoffeeScript code. It includes in it non-obvious fixes to some JavaScript gotchas.

Note: in the podcast JavaScript Jabber Jeremy Ashkenas discusses why this particular class definition is used.

#Conclusion There are loads of other things that I like about CoffeeScript, but the things I discussed in this post are the reasons I love CoffeeScript. They remove the ugliest parts of JavaScript to show its real power. Other things like list comprehensions, for loops, array slicing, splats... will have to wait for another post.

#Learn More Go to http://coffeescript.org/ and click Try CoffeeScript, listen to the JavaScript Jabber podcast on CoffeeScript,

also

The Little Book on CoffeeScript

Related Posts

comments powered by Disqus