CoffeeScript is a little language that compiles into JavaScript. Think of it as JavaScript's simpleminded 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 JavaScript equivalent, it's just another way of saying it.
Disclaimer:
CoffeeScript is just for fun and seriously alpha. There is no guarantee,
explicit or implied, of its suitability for any purpose. That said, it
compiles into pretty-printed JavaScript (the good parts) that can pass through
JSLint warning-free.
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.
Punctuation Primer
Functions and Invocation
Objects and Arrays
Assignment
Lexical Scoping and Variable Safety
Conditionals, Ternaries, and Conditional Assignment
Everything is an Expression
While Loops
Array Comprehensions
Array Slice Literals
Inheritance, and Calling Super from a Subclass
Embedded JavaScript
Switch/Case/Else
Try/Catch/Finally
Multiline Strings
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. So newlines can matter, but whitespace is not otherwise significant. Instead of using curly braces ({ }) to delimit blocks of code, a period (.) marks the end of a function, if statement, or try/catch.
Functions and Invocation Let's start with the best part, shall we? Function literals are my absolute favorite thing about CoffeeScript.
square: x => x * x. cube: x => square(x) * x.
var square = function(x) { return x * x; }; var cube = function(x) { return square(x) * x; };
Objects and Arrays Object and Array literals look very similar. When you spread out each assignment on a separate line, the commas are optional.
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 };
Assignment All assignment in CoffeeScript, whether to a variable or to an object property, uses a colon. Equal signs are only needed for mathy things.
greeting: "Hello CoffeeScript" difficulty: 0.5
var greeting = "Hello CoffeeScript"; var difficulty = 0.5;
Lexical Scoping and Variable Safety The CoffeeScript compiler takes care to make sure that all of your variables are properly defined within lexical scope — you never need to declare 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 new_num, in the last line.
Conditionals, Ternaries, and Conditional Assignment
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();
Everything is an Expression You might have noticed how even though we don't add return statements to CoffeScript functions, they nonetheless return their final value. The CoffeeScript compiler tries to make sure that every little language construct can be used as an expression.
grade: student => if student.excellent_work "A+" else if student.okay_stuff "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 "B"; } else { return "C"; } }; var eldest = 24 > 21 ? "Liz" : "Ike";
When compiling a function definition, CoffeeScript tries to push down the return statement to each of the potential final lines of the function. It uses the same mechanism to push down assignment statements. If statement are compiled into ternary operators when possible, so that they can be used as expressions.
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(); }
Array Comprehensions Most of your looping needs should be handled by array comprehensions. They replace (and compile into) for loops, handling each/forEach style loops, as well as select/filter. Unlike for loops, array comprehensions are expressions, and can be returned and assigned.
# 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.
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; 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 a literal 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);
Inheritance, and 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 (Base2, Prototype ).
Animal: => . Animal.prototype.move: meters => alert(this.name + " moved " + meters + "m."). Snake: name => this.name: name. Snake extends new Animal() Snake.prototype.move: => alert("Slithering...") super(5). Horse: name => this.name: name. Horse extends 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.
js: => `alert("Hello JavaScript");`. js() if 10 > 9
var js = function() { return alert("Hello JavaScript"); }; if (10 > 9) { js(); }
Switch/Case/Else Switch statements in JavaScript are fundamentally broken. You can only do string comparisons, and need to break at the end of each case statment to prevent falling through to the default case. CoffeeScript compiles switch statements into if-else chains, allowing you to compare any object (via ===), preventing fall-through, and resulting in a returnable expression.
switch day case "Tuesday" then eat_breakfast() case "Wednesday" then go_to_the_park() case "Saturday" if day is bingo_day then go_to_bingo(). 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") { day === bingo_day ? go_to_bingo() : null; } else if (day === "Sunday") { go_to_church(); } else { go_to_work(); }
Try/Catch/Finally Try/catch statements 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...";