Introduction

CoffeeScript is a neat little language that attempts to simplify and beautify the ugly parts of JavaScript. CoffeeScript has become very popular both inside and outside the Rails world due to the fact that it compiles down to JavaScript and is very simple and elegant to use. In this series of articles we will learn to write in CoffeeScript. For the purposes of these articles, we assume you have some familiarity with JavaScript. Let's get started.

Installation & Setup

If you are using Rails, CoffeeScript is the default language and you can use the built in CoffeeScript compiler if you'd like, otherwise we will need to install CoffeeScript. In order to do this, first we will need to install Node.js if it isn't already installed. Node.js provides a convenient package management tool called npm that allows you to quickly and easily install various packages such as CoffeeScript right from the terminal. To install Node.js you can either grab the generic binaries from http://nodejs.org/download/, or you can install Node.js using your favorite package manager. (Details here: https://github.com/joyent/node/wiki/Installing-Node.js-via-package-manager)

Once Node.js is installed you should have access to the npm command. Run the command below to install CoffeeScript:

Terminal Commands:

npm install -g coffee-script

Note that if you have problems running npm, try closing/reopening all of your terminal sessions and try again. Also make sure npm is properly added to your path.

The Basics

Once you have CoffeeScript installed, you will have access to the coffee command. The coffee command is used to compile CoffeeScript into JavaScript. Let's try this now. In a new file called alert.coffee, add in the following code.

alert.coffee:

alert "hi"

Now run the following command to compile alert.coffee into alert.js.

Terminal commands:

coffee -c alert.coffee

If all goes well, a file called alert.js will be created that looks similar to this the following code.

alert.js:

// Generated by CoffeeScript 1.8.0
(function() {
  alert("hi");

}).call(this);

The coffee command automatically compiled our code to JavaScript, which we can then include on our page. In this case, our code was a simple line of code that would pop up an alert that says hi.

In the example listed earlier, you'll notice that we didn't wrap "hi" in parenthesis. This is because in most cases, parenthesis are optional in CoffeeScript. This means your code can be much more clutter free.

Functions

Let's try another example. Let's create a simple function that shows a hello world alert. Open up your alert.coffee file again and modify it so that it looks like the code listed below.

alert.coffee:

helloWorld ->
  alert "hello world!"

Whoa what's this? Missing curly braces? Some weird arrow thing? First things first. The -> (skinny arrow) and => (fat arrow) are used to designate functions. This is functionally similar to doing:


function helloWorld() {
...
}

Curly braces are also optional in CoffeeScript, with indentation being used instead. This allows for much cleaner looking code.

Now if we look at the generated source code, we'll see a bit of a surprise:

alert.js:

// Generated by CoffeeScript 1.8.0
(function() {
  helloWorld(function() {
    return alert("hello world!");
  });

}).call(this);

It looks like our helloWorld function is attempting to return the value of the alert function. Why is this? CoffeeScript attempts to treat everything as an expression and the final value is almost always returned. The simplest way to correct the above issue would be to modify our CoffeeScript code to look like this:

alert.coffee:

helloWorld ->
  alert "hello world!"
  false

This makes your function return false instead:

alert.js:

// Generated by CoffeeScript 1.8.0
(function() {
  helloWorld(function() {
    alert("hello world!");
    return false;
  });

}).call(this);

What about variables? Well variables are declared sans the var keyword, var is reserved by CoffeeScript. To declare a variable you simply do:


number = 42

This would translate to the following code if you compiled it:


// Generated by CoffeeScript 1.8.0
(function() {
  var number;

  number = 42;

}).call(this);

You can do the same with arrays:


numberArray = [1,2,3,4,5,6,7,8,9]

Which is equivalent to:


// Generated by CoffeeScript 1.8.0
(function() {
  var numberArray;

  numberArray = [1, 2, 3, 4, 5, 6, 7, 8, 9];

}).call(this);

Conditional Statements

CoffeeScript contains interesting possibilities when it comes to conditional statements. Let's start with a basic if/else:


hello = true

if myVar
  alert "hello world!"
else
  alert "goodbye"

Which translates to:


// Generated by CoffeeScript 1.8.0
(function() {
  var hello;

  hello = true;

  if (myVar) {
    alert("hello world!");
  } else {
    alert("goodbye");
  }

}).call(this);

Right away notice how much cleaner that the if statement is without parenthesis or curly braces. However, this is just the beginning. Try out the code listed below.


hello = true

alert "hello world" if hello

Compiling this translates to:


// Generated by CoffeeScript 1.8.0
(function() {
  var hello;

  hello = true;

  if (hello) {
    alert("hello world");
  }

}).call(this);

CoffeeScript allows you to be very free flowing with your code. It gets even better:


hello = true

alert "hello world" unless hello is not yes

A couple things to note here. First, the unless keyword works just like the opposite of the if statement. The code listed above compiles to this:


// Generated by CoffeeScript 1.8.0
(function() {
  var hello;

  hello = true;

  if (hello !== !true) {
    alert("hello world");
  }

}).call(this);

The if statement above says 'if hello does not equal not true (i.e. it equals false or some other value).

The second thing you'll notice is the use of 'is not yes'. CoffeeScript includes a number of aliases for various JavaScript operators, which are listed below:

CoffeeScriptJavaScript
is===
isnt!==
not!
and&&
or||
true, yes, ontrue
false, no, offfalse
@, thisthis
ofin
inno JS equivalent
a ** bMath.pow(a, b)
a // bMath.floor(a / b)
a %% b(a % b + b) % b

These operators allow us to create more english looking statements.

Switch Statements

In CoffeeScript, switch statements have a much cleaner syntax. Take the example listed below:


day = "Mon"

response = switch day
  when "Mon" then "Boring Mondays"
  when "Tue" then "Wasn't yesterday Monday?"
  when "Wed" then "Two more days till Friday!"
  when "Thu" then "Happy thursday!"
  when "Fri", "Sat" then "Whoohoo!  The weekend is here!"
  when "Sun" then "Drat! Tomorrow is monday!"
  else "That's not a day!"

alert(response)

The code above takes a given value and returns it's appropriate response. This translates to:


// Generated by CoffeeScript 1.8.0
(function() {
  var day, response;

  day = "Mon";

  response = (function() {
    switch (day) {
      case "Mon":
        return "Boring Mondays";
      case "Tue":
        return "Wasn't yesterday Monday?";
      case "Wed":
        return "Two more days till Friday!";
      case "Thu":
        return "Happy thursday!";
      case "Fri":
      case "Sat":
        return "Whoohoo!  The weekend is here!";
      case "Sun":
        return "drat! Tomorrow is monday!";
      default:
        return "That's not a day!";
    }
  })();

  alert(response);

}).call(this);

In our next article in the series we will look at some advanced features of CoffeeScript, including Classes, Inheritance, and much more! That's it! Thanks for reading!

Resources