CoffeeScript

CoffeeScript is a little language that compiles into JavaScript. Think of it as JavaScript's less ostentatious kid brother — the same genes, the same accent, but a different sense of style. Apart from a handful of bonus goodies, statements in CoffeeScript correspond one-to-one with their equivalent in JavaScript, it's just another way of saying it.

Disclaimer: CoffeeScript is just for fun and seriously alpha. I'm sure that there are still plenty of holes in the lexer and leaks in the syntax. There is no guarantee, explicit or implied, of its suitability for any purpose. That said, it compiles into clean JavaScript (the good parts) that can use existing JavaScript libraries seamlessly, and passes through JSLint without warnings. The compiled output is quite readable — pretty-printed, with comments preserved intact.

Table of Contents

Mini Overview
Installation and Usage
Punctuation Primer
Functions and Invocation
Assignment
Objects and Arrays
Lexical Scoping and Variable Safety
Conditionals, Ternaries, and Conditional Assignment
Everything is an Expression
Aliases
While Loops
Array Comprehensions
Array Slice Literals
Calling Super from a Subclass
Embedded JavaScript
Switch/Case/Else
Try/Catch/Finally
Multiline Strings

Mini Overview

CoffeeScript on the left, compiled JavaScript output on the right.

# Assignment:
number: 42
opposite_day: true

# Conditions:
number: -42 if opposite_day

# Functions:
square: x => x * x.

# Arrays:
list: [1, 2, 3, 4, 5]

# Objects:
math: {
  root:   Math.sqrt
  square: square
  cube:   x => x * square(x).
}

# Array comprehensions:
cubed_list: math.cube(num) for num in list.
// Assignment:
var number = 42;
var opposite_day = true;
// Conditions:
if (opposite_day) {
  number = -42;
}
// Functions:
var square = function(x) {
  return x * x;
};
// Arrays:
var list = [1, 2, 3, 4, 5];
// Objects:
var math = {
  root: Math.sqrt,
  square: square,
  cube: function(x) {
    return x * square(x);
  }
};
// Array comprehensions:
var cubed_list;
var a = list;
var d = [];
for (var b=0, c=a.length; b<c; b++) {
  var num = a[b];
  d[b] = math.cube(num);
}
cubed_list = d;

Installation and Usage

sudo gem install coffee-script

Installing the gem provides the coffee-script command, which can be used to compile CoffeeScript .cs files into JavaScript, as well as debug them. By default, coffee-script writes out the JavaScript as .js files in the same directory, but output can be customized with the following options:

-o, --output [DIR] Write out all compiled JavaScript files into the specified directory.
-w, --watch Watch the modification times of the coffee-scripts, recompiling as soon as a change occurs.
-p, --print Instead of writing out the JavaScript as a file, print it directly to stdout.
-l, --lint If the jsl (JavaScript Lint) command is installed, use it to check the compilation of a CoffeeScript file. (Handy in conjunction with --watch)
-e, --eval Compile and print a little snippet of CoffeeScript directly from the command line (or from stdin). For example:
coffee-script -e "square: x => x * x."
-t, --tokens Instead of parsing the CoffeeScript, just lex it, and print out the token stream: [:IDENTIFIER, "square"], [":", ":"], [:PARAM, "x"] ...
-v, --verbose As the JavaScript is being generated, print out every step of code generation, including lexical scope and the node in the AST.
--install-bundle Install the TextMate bundle for CoffeeScript syntax highlighting.

Examples:

coffee-script path/to/script.cs
coffee-script --watch --lint experimental.cs
coffee-script --print app/scripts/*.cs > concatenation.js

Language Reference

This document is structured so that it can be read from top to bottom, if you like. Later sections use ideas and syntax previously introduced. Familiarity with JavaScript is assumed. In all of the following examples, the source CoffeeScript is provided on the left, and the direct compilation into JavaScript is on the right.

Punctuation Primer You don't need to use semicolons ; to terminate expressions, ending the line will do just as well. All other whitespace is not significant. Instead of using curly braces { } to delimit a block of code, use a period . to mark the end of a block, for functions, if-statements, switch, and try/catch.

Functions and Invocation Functions are defined by a list of parameters, an arrow, and the function body. The empty function looks like this: =>.

square: x => x * x.
cube:   x => square(x) * x.
var square = function(x) {
  return x * x;
};
var cube = function(x) {
  return square(x) * x;
};

Assignment Use a colon : to assign, as in JSON. Equal signs are only needed for mathy things.

greeting: "Hello CoffeeScript"
difficulty: 0.5
var greeting = "Hello CoffeeScript";
var difficulty = 0.5;

Objects and Arrays Object and Array literals look very similar to their JavaScript cousins. When you spread out each assignment on a separate line, the commas are optional. In this way, assigning object properties looks the same as assigning local variables.

song: ["do", "re", "mi", "fa", "so"]
ages: {
  max: 10
  ida: 9
  tim: 11
}
var song = ["do", "re", "mi", "fa", "so"];
var ages = {
  max: 10,
  ida: 9,
  tim: 11
};

Lexical Scoping and Variable Safety The CoffeeScript compiler takes care to make sure that all of your variables are properly declared within lexical scope — you never need to write var yourself.

num: 1
change_numbers: =>
  num: 2
  new_num: 3.
new_num: change_numbers()
var num = 1;
var change_numbers = function() {
  num = 2;
  var new_num = 3;
  return new_num;
};
var new_num = change_numbers();

Notice how the variables are declared with var the first time they appear. The second reference of num, within the function, is not redeclared because num is still in scope. As opposed to the second occurrence of new_num, in the last line.

Although suppressed within this documentation for clarity, all CoffeeScript output is wrapped in an anonymous function: (function(){ ... })(); This safety wrapper, combined with the automatic generation of the var keyword, make it exceedingly difficult to pollute the global namespace by accident.

Conditionals, Ternaries, and Conditional Assignment If/else statements can be written without the use of parenthesis and curly brackets. As with functions and other block expressions, conditionals are closed with periods. No period is necessary when using the single-line postfix form, with the if at the end.

mood: greatly_improved if singing

if happy and knows_it
  claps_hands()
  cha_cha_cha().

date: if friday then sue else jill.

expensive ||: do_the_math()
var mood;
if (singing) {
  mood = greatly_improved;
}
if (happy && knows_it) {
  claps_hands();
  cha_cha_cha();
}
var date = friday ? sue : jill;
expensive = expensive || do_the_math();

CoffeeScript includes the conditional assignment operators: ||:, which only assigns a value to a variable if the variable's current value is falsy, and &&:, which only replaces the value of truthy variables.

Everything is an Expression (at least, as much as possible) You might have noticed how even though we don't add return statements to CoffeeScript functions, they nonetheless return their final value. The CoffeeScript compiler tries to make sure that all statements in the language can be used as expressions. Watch how the return gets pushed down into each possible branch of execution, in the function below.

grade: student =>
  if student.excellent_work
    "A+"
  else if student.okay_stuff
    if student.tried_hard then "B" else "B-".
  else
    "C"..

eldest: if 24 > 21 then "Liz" else "Ike".
var grade = function(student) {
  if (student.excellent_work) {
    return "A+";
  } else if (student.okay_stuff) {
    return student.tried_hard ? "B" : "B-";
  } else {
    return "C";
  }
};
var eldest = 24 > 21 ? "Liz" : "Ike";

The same mechanism is used to push down assignment through switch statements, and if-elses (although the ternary operator is preferred).

Aliases Because the == operator frequently causes undesirable coercion, is intransitive, and has a different meaning than in other languages, CoffeeScript compiles == into ===, and != into !==. In addition, is compiles into ===, and aint into !==.

You can use not as an alias for !.

As in YAML, on and yes are the same as boolean true, while off and no are boolean false.

For single-line statements, unless can be used as the inverse of if.

launch() if ignition is on

volume: 10 if band aint spinal_tap

let_the_wild_rumpus_begin() unless answer is no
if (ignition === true) {
  launch();
}
var volume;
if (band !== spinal_tap) {
  volume = 10;
}
if (!(answer === false)) {
  let_the_wild_rumpus_begin();
}

While Loops The only low-level loop that CoffeeScript provides is the while loop.

while demand > supply
  sell()
  restock().

while supply > demand then buy().
while (demand > supply) {
  sell();
  restock();
}
while (supply > demand) {
  buy();
}

Other JavaScript loops, such as for loops and do-while loops can be mimicked by variations on while, but the hope is that you won't need to do that with CoffeeScript, either because you're using each (forEach) style iterators, or...

Array Comprehensions For your looping needs, CoffeeScript provides array comprehensions similar to Python's. They replace (and compile into) for loops, with optional guard clauses and the value of the current array index. Unlike for loops, array comprehensions are expressions, and can be returned and assigned. They should be able to handle most places where you otherwise would use a loop, each/forEach, map, or select/filter.

# Eat lunch.
lunch: food.eat() for food in ['toast', 'cheese', 'wine'].

# Zebra-stripe a table.
highlight(row) for row, i in table if i % 2 is 0.
// Eat lunch.
var lunch;
var a = ['toast', 'cheese', 'wine'];
var d = [];
for (var b=0, c=a.length; b<c; b++) {
  var food = a[b];
  d[b] = food.eat();
}
lunch = d;
// Zebra-stripe a table.
var e = table;
for (var f=0, g=e.length; f<g; f++) {
  var row = e[f];
  var i = f;
  i % 2 === 0 ? highlight(row) : null;
}

Array Slice Literals CoffeeScript includes syntax for extracting slices of arrays. The first argument is the index of the first element in the slice, and the second is the index of the last one.

nums: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
three_to_six: nums[3, 6]
var nums = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
var three_to_six = nums.slice(3, 6 + 1);

Calling Super from a Subclass JavaScript's prototypal inheritance has always been a bit of a brain-bender, with a whole family tree of libraries that provide a cleaner syntax for classical inheritance on top of JavaScript's prototypes: Base2, Prototype.js, JS.Class, etc. The libraries provide syntactic sugar, but the built-in inheritance would be completely usable if it weren't for one small exception: it's very awkward to call super, the prototype object's implementation of the current function. CoffeeScript converts super() calls into calls against the immediate ancestor's method of the same name.

Animal: => .
Animal.prototype.move: meters =>
  alert(this.name + " moved " + meters + "m.").

Snake: name => this.name: name.
Snake.prototype: new Animal()
Snake.prototype.move: =>
  alert("Slithering...")
  super(5).

Horse: name => this.name: name.
Horse.prototype: new Animal()
Horse.prototype.move: =>
  alert("Galloping...")
  super(45).

sam: new Snake("Sammy the Python")
tom: new Horse("Tommy the Palomino")

sam.move()
tom.move()




var Animal = function() {
};
Animal.prototype.move = function(meters) {
  return alert(this.name + " moved " + meters + "m.");
};
var Snake = function(name) {
  this.name = name;
};
Snake.prototype = new Animal();
Snake.prototype.move = function() {
  alert("Slithering...");
  return this.constructor.prototype.move.call(this, 5);
};
var Horse = function(name) {
  this.name = name;
};
Horse.prototype = new Animal();
Horse.prototype.move = function() {
  alert("Galloping...");
  return this.constructor.prototype.move.call(this, 45);
};
var sam = new Snake("Sammy the Python");
var tom = new Horse("Tommy the Palomino");
sam.move();
tom.move();

Embedded JavaScript If you ever need to interpolate literal JavaScript snippets, you can use backticks to pass JavaScript straight through.

hi: `function() {
  return [document.title, "Hello JavaScript"].join(": ");
}`

var hi = function() {
return [document.title, "Hello JavaScript"].join(": ");
};

Switch/Case/Else Switch statements in JavaScript are rather broken. You can only do string comparisons, and need to remember to break at the end of every case statement to avoid accidentally falling through to the default case. CoffeeScript compiles switch statements into JavaScript if-else chains, allowing you to compare any object (via ===), preventing fall-through, and resulting in a returnable, assignable expression. To specify the default case, just use else.

switch day
case "Tuesday"   then eat_breakfast()
case "Wednesday" then go_to_the_park()
case "Saturday"
  if day is bingo_day
    go_to_bingo()
    go_dancing().
case "Sunday"    then go_to_church()
else go_to_work().
if (day === "Tuesday") {
  eat_breakfast();
} else if (day === "Wednesday") {
  go_to_the_park();
} else if (day === "Saturday") {
  if (day === bingo_day) {
    go_to_bingo();
    go_dancing();
  }
} else if (day === "Sunday") {
  go_to_church();
} else {
  go_to_work();
}

Try/Catch/Finally Try/catch statements are just about the same as JavaScript (although they work as expressions). No braces required.

try
  all_hell_breaks_loose()
  cats_and_dogs_living_together()
catch error
  print(error)
finally
  clean_up().
try {
  all_hell_breaks_loose();
  cats_and_dogs_living_together();
} catch (error) {
  print(error);
} finally {
  clean_up();
}

Multiline Strings Multiline strings are allowed in CoffeeScript.

moby_dick: "Call me Ishmael. Some years ago --
never mind how long precisely -- having little
or no money in my purse, and nothing particular
to interest me on shore, I thought I would sail
about a little and see the watery part of the
world..."

var moby_dick = "Call me Ishmael. Some years ago -- \
never mind how long precisely -- having little \
or no money in my purse, and nothing particular \
to interest me on shore, I thought I would sail \
about a little and see the watery part of the \
world...";