CoffeeScript is a little language that compiles into JavaScript. Think of it as JavaScript's less ostentatious kid brother — the same genes, roughly the same height, 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. Until it reaches 1.0, there are no guarantees that the syntax won't change between versions. 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.
Latest Version: 0.6.0
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 } # Splats: race: (winner, runners...) -> print winner, runners # Existence: alert "I knew it!" if elvis? # Array comprehensions: cubed_list: math.cube num for num in list
var _a, _b, _c, _d, cubed_list, list, math, num, number, opposite_day, race, square; var __slice = Array.prototype.slice; // Assignment: number = 42; opposite_day = true; // Conditions: if (opposite_day) { number = -42; } // Functions: square = function square(x) { return x * x; }; // Arrays: list = [1, 2, 3, 4, 5]; // Objects: math = { root: Math.sqrt, square: square, cube: function cube(x) { return x * square(x); } }; // Splats: race = function race(winner) { var runners; runners = __slice.call(arguments, 1, arguments.length - 0); return print(winner, runners); }; // Existence: if ((typeof elvis !== "undefined" && elvis !== null)) { alert("I knew it!"); } // Array comprehensions: cubed_list = (function() { _a = []; _c = list; for (_b = 0, _d = _c.length; _b < _d; _b++) { num = _c[_b]; _a.push(math.cube(num)); } return _a; }).call(this);
For a longer CoffeeScript example, check out Underscore.coffee, a port of the Underscore.js library of helper functions. Underscore.coffee can pass the entire Underscore.js test suite. The CoffeeScript version is faster than the original for a number of methods (in general, due to the speed of CoffeeScript's array comprehensions), and after being minified and gzipped, is only 241 bytes larger than the original JavaScript version. Additional examples are included in the source repository, inside the examples folder.
The CoffeeScript compiler is written in pure CoffeeScript, using a small DSL on top of the Jison parser generator, and is available as a Node.js utility. The core compiler however, does not depend on Node, and can be run in other server-side-JavaScript environments, or in the browser (see "Try CoffeeScript", above). This may be helpful, as Node only run on flavors of nix, and not Windows, for the time being.
To install, first make sure you have a working copy of the latest tagged version of Node.js, currently 0.1.33 or higher. Then clone the CoffeeScript source repository from GitHub, or download the latest release: 0.6.0. To install the CoffeeScript compiler system-wide under /usr/local, open the directory and run:
sudo bin/cake install
This provides the coffee command, which will execute CoffeeScripts under Node.js by default, but is also used to compile CoffeeScript .coffee files into JavaScript, or to run an an interactive REPL. When compiling to JavaScript, coffee writes the output as .js files in the same directory by default, but output can be customized with the following options:
-c, --compile |
Compile a .coffee script into a .js JavaScript file of the same name. |
-i, --interactive |
Launch an interactive CoffeeScript session to try short snippets. More pleasant if wrapped with rlwrap. |
-o, --output [DIR] |
Write out all compiled JavaScript files into the specified directory. Use in conjunction with --compile or --watch. |
-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) |
-s, --stdio |
Pipe in CoffeeScript to STDIN and get back JavaScript over STDOUT.
Good for use with processes written in other languages. An example: cat src/cake.coffee | coffee -sc |
-e, --eval |
Compile and print a little snippet of CoffeeScript directly from the
command line. For example: coffee -e "puts num for num in [10..1]" |
--no-wrap |
Compile the JavaScript without the top-level function safety wrapper. (Used for CoffeeScript as a Node.js module.) |
-t, --tokens |
Instead of parsing the CoffeeScript, just lex it, and print out the token stream: [IDENTIFIER square] [ASSIGN :] [PARAM_START (] ... |
-n, --nodes |
Instead of compiling the CoffeeScript, just lex and parse it, and print
out the parse tree:
Expressions Assign Value "square" Code "x" Op * Value "x" Value "x" |
Examples:
coffee -c path/to/script.coffee coffee --interactive coffee --watch --lint experimental.coffee coffee --print app/scripts/*.coffee > concatenation.js
This reference 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.
Many of the examples can be run (where it makes sense) by pressing the "run" button towards the bottom right. You can also paste examples into "Try CoffeeScript" in the toolbar, and play with them from there.
Significant Whitespace CoffeeScript uses Python-style significant whitespace: You don't need to use semicolons ; to terminate expressions, ending the line will do just as well. Semicolons can still be used to fit multiple expressions onto a single line. Instead of using curly braces { } to delimit blocks of code (like functions, if-statements, switch, and try/catch), use indentation.
You don't need to use parentheses to invoke a function if you're passing
arguments:
print "coffee"
You can use newlines to break up your expression into smaller pieces, as long as CoffeeScript can determine that the line hasn't finished yet, because it ends with an operator or a dot.
Functions and Invocation Functions are defined by a list of parameters, an arrow, and the function body. The empty function looks like this: -> All functions in CoffeeScript are named by default, for easier debugging.
square: (x) -> x * x cube: (x) -> square(x) * x
var cube, square; square = function square(x) { return x * x; }; cube = function cube(x) { return square(x) * x; };
If you'd like to assign a function literal to a variable, but not have it be named, just wrap the function definition in parentheses: ((x) -> x * x)
Assignment Use a colon : to assign, as in JSON. Equal signs are only needed for mathy things. While colons are preferred, the two may be used interchangeably, even within object literals.
greeting: "Hello CoffeeScript" difficulty: 0.5
var difficulty, greeting; greeting = "Hello CoffeeScript"; difficulty = 0.5;
All declaration of new variables is pushed up to the top of the nearest lexical scope, so that assignment may always be performed within expressions.
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, and can be moved around freely. Feel free to mix and match the two styles.
song: ["do", "re", "mi", "fa", "so"] ages: { max: 10 ida: 9 tim: 11 } matrix: [ 1, 0, 1 0, 0, 1 1, 1, 0 ]
var ages, matrix, song; song = ["do", "re", "mi", "fa", "so"]; ages = { max: 10, ida: 9, tim: 11 }; matrix = [1, 0, 1, 0, 0, 1, 1, 1, 0];
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: -> new_num: -1 num: 10 new_num: change_numbers()
var change_numbers, new_num, num; num = 1; change_numbers = function change_numbers() { var new_num; new_num = -1; num = 10; return num; }; new_num = change_numbers();
Notice how the all of the variable declarations have been pushed up to the top of the closest scope, the first time they appear. num is not redeclared within the inner function, because it's already in scope; the new_num within the function, on the other hand, should not be able to change the value of the external variable of the same name, and therefore has a declaration of its own.
This behavior is effectively identical to Ruby's scope for local variables. Because you don't have direct access to the var keyword, it's impossible to shadow an outer variable on purpose, you may only refer to it. So be careful that you're not reusing the name of an external variable accidentally, if you're writing a deeply nested function.
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.
If you'd like to create top-level variables for other scripts to use, attach them as properties on window, or on the exports object in CommonJS. The existential operator (below), gives you a reliable way to figure out where to add them, if you're targeting both CommonJS and the browser: root: exports ? this
Conditionals, Ternaries, and Conditional Assignment If/else statements can be written without the use of parentheses and curly brackets. As with functions and other block expressions, multi-line conditionals are delimited by indentation. There's also a handy postfix form, with the if or unless at the end.
CoffeeScript will compile if statements using the ternary operator when possible, to make it easier to use the result as an expression.
mood: greatly_improved if singing if happy and knows_it claps_hands() cha_cha_cha() date: if friday then sue else jill expensive: or do_the_math()
var date, expensive, mood; if (singing) { mood = greatly_improved; } if (happy && knows_it) { claps_hands(); cha_cha_cha(); } date = friday ? sue : jill; expensive = expensive || do_the_math();
You can assign a variable to a half-expression to perform an operation like Ruby's ||=, which only assigns a value to a variable if the variable's current value is falsy.
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 isnt into !==.
You can use not as an alias for !.
For logic, and compiles to &&, and or into ||.
Instead of a newline or semicolon, then can be used to separate conditions from expressions, in while, if/else, and switch/when statements.
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.
As a shortcut for this.property, you can use @property.
launch() if ignition is on volume: 10 if band isnt spinal_tap let_the_wild_rumpus_begin() unless answer is no if car.speed < speed_limit then accelerate() print "My name is " + @name
var volume; if (ignition === true) { launch(); } if (band !== spinal_tap) { volume = 10; } if (!(answer === false)) { let_the_wild_rumpus_begin(); } car.speed < speed_limit ? accelerate() : null; print("My name is " + this.name);
Splats... The JavaScript arguments object is a useful way to work with functions that accept variable numbers of arguments. CoffeeScript provides splats ..., both for function definition as well as invocation, making variable numbers of arguments a little bit more palatable.
gold: silver: the_field: "unknown" award_medals: (first, second, rest...) -> gold: first silver: second the_field: rest contenders: [ "Michael Phelps" "Liu Xiang" "Yao Ming" "Allyson Felix" "Shawn Johnson" "Roman Sebrle" "Guo Jingjing" "Tyson Gay" "Asafa Powell" "Usain Bolt" ] award_medals contenders... alert "Gold: " + gold alert "Silver: " + silver alert "The Field: " + the_field
var award_medals, contenders, gold, silver, the_field; var __slice = Array.prototype.slice; gold = (silver = (the_field = "unknown")); award_medals = function award_medals(first, second) { var rest; rest = __slice.call(arguments, 2, arguments.length - 0); gold = first; silver = second; the_field = rest; return the_field; }; contenders = ["Michael Phelps", "Liu Xiang", "Yao Ming", "Allyson Felix", "Shawn Johnson", "Roman Sebrle", "Guo Jingjing", "Tyson Gay", "Asafa Powell", "Usain Bolt"]; award_medals.apply(this, contenders); alert("Gold: " + gold); alert("Silver: " + silver); alert("The Field: " + the_field);
While Loops The only low-level loop that CoffeeScript provides is the while loop. The main difference from JavaScript is that the while loop can be used as an expression, returning an array containing the result of each iteration through the loop.
# Econ 101 if this.studying_economics while supply > demand then buy() while supply < demand then sell() # Nursery Rhyme num: 6 lyrics: while num -= 1 num + " little monkeys, jumping on the bed. One fell out and bumped his head."
var _a, lyrics, num; // Econ 101 if (this.studying_economics) { while (supply > demand) { buy(); } while (supply < demand) { sell(); } } // Nursery Rhyme num = 6; lyrics = (function() { _a = []; while (num -= 1) { _a.push(num + " little monkeys, jumping on the bed. \ One fell out and bumped his head."); } return _a; }).call(this);
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...
Comprehensions (Arrays, Objects, and Ranges) 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: eat food for food in ['toast', 'cheese', 'wine'] # Naive collision detection. for roid in asteroids for roid2 in asteroids when roid isnt roid2 roid.explode() if roid.overlaps roid2
var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, food, lunch, roid, roid2; // Eat lunch. lunch = (function() { _a = []; _c = ['toast', 'cheese', 'wine']; for (_b = 0, _d = _c.length; _b < _d; _b++) { food = _c[_b]; _a.push(eat(food)); } return _a; }).call(this); // Naive collision detection. _f = asteroids; for (_e = 0, _g = _f.length; _e < _g; _e++) { roid = _f[_e]; _i = asteroids; for (_h = 0, _j = _i.length; _h < _j; _h++) { roid2 = _i[_h]; if (roid !== roid2) { if (roid.overlaps(roid2)) { roid.explode(); } } } }
If you know the start and end of your loop, or would like to step through in fixed-size increments, you can use a range to specify the start and end of your comprehension. (The long line-breaking "for" definitions in the compiled JS below allow ranges to count downwards, as well as upwards).
countdown: num for num in [10..1] egg_delivery: -> for i in [0...eggs.length] by 12 dozen_eggs: eggs[i...i+12] deliver new egg_carton(dozen)
var _a, _b, _c, _d, countdown, egg_delivery, num; countdown = (function() { _a = []; _c = 10; _d = 1; for (_b = 0, num = _c; (_c <= _d ? num <= _d : num >= _d); (_c <= _d ? num += 1 : num -= 1), _b++) { _a.push(num); } return _a; }).call(this); egg_delivery = function egg_delivery() { var _e, _f, _g, _h, dozen_eggs, i; _e = []; _g = 0; _h = eggs.length; for (_f = 0, i = _g; (_g <= _h ? i < _h : i > _h); (_g <= _h ? i += 12 : i -= 12), _f++) { _e.push((function() { dozen_eggs = eggs.slice(i, i + 12); return deliver(new egg_carton(dozen)); }).call(this)); } return _e; };
Comprehensions can also be used to iterate over the keys and values in an object. Use of to signal comprehension over the properties of an object instead of the values in an array.
years_old: {max: 10, ida: 9, tim: 11} ages: for child, age of years_old child + " is " + age
var _a, _b, age, ages, child, years_old; var __hasProp = Object.prototype.hasOwnProperty; years_old = { max: 10, ida: 9, tim: 11 }; ages = (function() { _a = []; _b = years_old; for (child in _b) { if (__hasProp.call(_b, child)) { age = _b[child]; _a.push(child + " is " + age); }} return _a; }).call(this);
Array Slicing and Splicing with Ranges CoffeeScript borrows Ruby's range syntax for extracting slices of arrays. With two dots (3..5), the range is inclusive: the first argument is the index of the first element in the slice, and the second is the index of the last one. Three dots signify a range that excludes the end.
numbers: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] three_to_six: numbers[3..6] numbers_copy: numbers[0...numbers.length]
var numbers, numbers_copy, three_to_six; numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; three_to_six = numbers.slice(3, 6 + 1); numbers_copy = numbers.slice(0, numbers.length);
The same syntax can be used with assignment to replace a segment of an array with new values (to splice it).
numbers: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] numbers[3..6]: [-3, -4, -5, -6]
var numbers; numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; numbers.splice.apply(numbers, [3, 6 - 3 + 1].concat([-3, -4, -5, -6]));
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 eldest, grade; grade = function grade(student) { if (student.excellent_work) { return "A+"; } else if (student.okay_stuff) { if (student.tried_hard) { return "B"; } else { return "B-"; } } else { return "C"; } }; eldest = 24 > 21 ? "Liz" : "Ike";
Even though functions will always return their final value, it's both possible and encouraged to return early from a function body writing out the explicit return (return value), when you know that you're done.
Because variable declarations occur at the top of scope, assignment can be used within expressions, even for variables that haven't been seen before:
six: (one: 1) + (two: 2) + (three: 3)
var one, six, three, two; six = (one = 1) + (two = 2) + (three = 3);
Things that would otherwise be statements in JavaScript, when used as part of an expression in CoffeeScript, are converted into expressions by wrapping them in a closure. This lets you do useful things, like assign the result of a comprehension to a variable:
# The first ten global properties. globals: (name for name of window)[0...10]
var _a, _b, globals, name; var __hasProp = Object.prototype.hasOwnProperty; // The first ten global properties. globals = (function() { _a = []; _b = window; for (name in _b) { if (__hasProp.call(_b, name)) { _a.push(name); }} return _a; }).call(this).slice(0, 10);
As well as silly things, like passing a try/catch statement directly into a function call:
alert( try nonexistent / undefined catch error "And the error is ... " + error )
alert((function() { try { return nonexistent / undefined; } catch (error) { return "And the error is ... " + error; } }).call(this));
There are a handful of statements in JavaScript that can't be meaningfully converted into expressions, namely break, continue, and return. If you make use of them within a block of code, CoffeeScript won't try to perform the conversion.
The Existential Operator It's a little difficult to check for the existence of a variable in JavaScript. if (variable) ... comes close, but fails for zero, the empty string, and false. CoffeeScript's existential operator ? returns true unless a variable is null or undefined, which makes it analogous to Ruby's nil?
It can also be used for safer conditional assignment than ||= provides, for cases where you may be handling numbers or strings.
solipsism: true if mind? and not world? speed ?= 140
var solipsism, speed; if ((typeof mind !== "undefined" && mind !== null) && !(typeof world !== "undefined" && world !== null)) { solipsism = true; } speed = (typeof speed !== "undefined" && speed !== null) ? speed : 140;
The accessor variant of the existential operator ?. can be used to soak up null references in a chain of properties. Use it instead of the dot accessor . in cases where the base value may be null or undefined. If all of the properties exist then you'll get the expected result, if the chain is broken, undefined is returned instead of the TypeError that would be raised otherwise.
lottery.draw_winner()?.address?.zipcode
var _a; (_a = lottery.draw_winner()) == undefined ? undefined : _a.address == undefined ? undefined : _a.address.zipcode;
Soaking up nulls is similar to Ruby's andand gem, and to the safe navigation operator in Groovy.
Classes, Inheritance, and Super 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 a couple of small exceptions: it's awkward to call super (the prototype object's implementation of the current function), and it's awkward to correctly set the prototype chain.
Instead of repetitively attaching functions to a prototype, CoffeeScript provides a basic class structure that allows you to name your class, set the superclass, assign prototypal properties, and define the constructor, in a single assignable expression.
class Animal move: (meters) -> alert @name + " moved " + meters + "m." class Snake extends Animal constructor: (name) -> @name: name move: -> alert "Slithering..." super 5 class Horse extends Animal constructor: (name) -> @name: name move: -> alert "Galloping..." super 45 sam: new Snake "Sammy the Python" tom: new Horse "Tommy the Palomino" sam.move() tom.move()
var Animal, Horse, Snake, sam, tom; var __extends = function(child, parent) { var ctor = function(){ }; ctor.prototype = parent.prototype; child.__superClass__ = parent.prototype; child.prototype = new ctor(); child.prototype.constructor = child; }; Animal = function Animal() { }; Animal.prototype.move = function move(meters) { return alert(this.name + " moved " + meters + "m."); }; Snake = function Snake(name) { this.name = name; return this; }; __extends(Snake, Animal); Snake.prototype.move = function move() { alert("Slithering..."); return Snake.__superClass__.move.call(this, 5); }; Horse = function Horse(name) { this.name = name; return this; }; __extends(Horse, Animal); Horse.prototype.move = function move() { alert("Galloping..."); return Horse.__superClass__.move.call(this, 45); }; sam = new Snake("Sammy the Python"); tom = new Horse("Tommy the Palomino"); sam.move(); tom.move();
If structuring your prototypes classically isn't your cup of tea, CoffeeScript provides a couple of lower-level conveniences. The extends operator helps with proper prototype setup, :: gives you quick access to an object's prototype, and super() is converted into a call against the immediate ancestor's method of the same name.
String::dasherize: -> this.replace(/_/g, "-")
String.prototype.dasherize = function dasherize() { return this.replace(/_/g, "-"); };
Finally, you may assign Class-level (static) properties within a class
definition by using
@property: value
Pattern Matching (Destructuring Assignment) To make extracting values from complex arrays and objects more convenient, CoffeeScript implements ECMAScript Harmony's proposed destructuring assignment syntax. When you assign an array or object literal to a value, CoffeeScript breaks up and matches both sides against each other, assigning the values on the right to the variables on the left. In the simplest case, it can be used for parallel assignment:
bait: 1000 and_switch: 0 [bait, and_switch]: [and_switch, bait]
var _a, and_switch, bait; bait = 1000; and_switch = 0; _a = [and_switch, bait]; bait = _a[0]; and_switch = _a[1];
But it's also helpful for dealing with functions that return multiple values.
weather_report: (location) -> # Make an Ajax request to fetch the weather... [location, 72, "Mostly Sunny"] [city, temp, forecast]: weather_report "Berkeley, CA"
var _a, city, forecast, temp, weather_report; weather_report = function weather_report(location) { // Make an Ajax request to fetch the weather... return [location, 72, "Mostly Sunny"]; }; _a = weather_report("Berkeley, CA"); city = _a[0]; temp = _a[1]; forecast = _a[2];
Pattern matching can be used with any depth of array and object nesting, to help pull out deeply nested properties.
futurists: { sculptor: "Umberto Boccioni" painter: "Vladimir Burliuk" poet: { name: "F.T. Marinetti" address: [ "Via Roma 42R" "Bellagio, Italy 22021" ] } } {poet: {name: poet, address: [street, city]}}: futurists
var _a, _b, _c, city, futurists, poet, street; futurists = { sculptor: "Umberto Boccioni", painter: "Vladimir Burliuk", poet: { name: "F.T. Marinetti", address: ["Via Roma 42R", "Bellagio, Italy 22021"] } }; _a = futurists; _b = _a.poet; poet = _b.name; _c = _b.address; street = _c[0]; city = _c[1];
Pattern matching can even be combined with splats.
tag: "<impossible>" [open, contents..., close]: tag.split("")
var _a, close, contents, open, tag; var __slice = Array.prototype.slice; tag = "<impossible>"; _a = tag.split(""); open = _a[0]; contents = __slice.call(_a, 1, _a.length - 1); close = _a[_a.length - 1];
Function binding In JavaScript, the this keyword is dynamically scoped to mean the object that the current function is attached to. If you pass a function as as callback, or attach it to a different object, the original value of this will be lost. If you're not familiar with this behavior, this Digital Web article gives a good overview of the quirks.
The fat arrow => can be used to both define a function, and to bind it to the current value of this, right on the spot. This is helpful when using callback-based libraries like Prototype or jQuery, for creating iterator functions to pass to each, or event-handler functions to use with bind. Functions created with the fat arrow are able to access properties of the this where they're defined.
Account: (customer, cart) -> @customer: customer @cart: cart $('.shopping_cart').bind 'click', (event) => @customer.purchase @cart
var Account; var __slice = Array.prototype.slice, __bind = function(func, obj, args) { return function() { return func.apply(obj || {}, args ? args.concat(__slice.call(arguments, 0)) : arguments); }; }; Account = function Account(customer, cart) { this.customer = customer; this.cart = cart; return $('.shopping_cart').bind('click', __bind(function(event) { return this.customer.purchase(this.cart); }, this)); };
If we had used -> in the callback above, @customer would have referred to the undefined "customer" property of the DOM element, and trying to call purchase() on it would have raised an exception.
If you have more custom needs for function binding, CoffeeScript includes the <- bind operator, which works the same as ECMAScript 5 and Prototype.js's Function#bind. The first argument is the this value, and the remainder are curried arguments. In the example below, we curry a jQuery request for a URL, and then execute the bound function with the missing callback argument.
url: "documentation/coffee/binding.coffee" get_source: jQuery.get <- jQuery, url get_source (response) -> alert response
var get_source, url; var __slice = Array.prototype.slice, __bind = function(func, obj, args) { return function() { return func.apply(obj || {}, args ? args.concat(__slice.call(arguments, 0)) : arguments); }; }; url = "documentation/coffee/binding.coffee"; get_source = __bind(jQuery.get, jQuery, [url]); get_source(function(response) { return alert(response); });
Embedded JavaScript Hopefully, you'll never need to use it, but if you ever need to intersperse snippets of JavaScript within your CoffeeScript, you can use backticks to pass it straight through.
hi: `function() { return [document.title, "Hello JavaScript"].join(": "); }`
var hi; hi = function() { return [document.title, "Hello JavaScript"].join(": "); };
Switch/When/Else Switch statements in JavaScript are rather broken. You can only do comparisons based on string equality, 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. The format is: switch condition, when clauses, else the default case.
As in Ruby, switch statements in CoffeeScript can take multiple values for each when clause. If any of the values match, the clause runs.
switch day when "Mon" then go_to_work() when "Tue" then go_to_the_park() when "Thu" then go_ice_fishing() when "Fri", "Sat" if day is bingo_day go_to_bingo() go_dancing() when "Sun" then go_to_church() else go_to_work()
if (day === "Mon") { go_to_work(); } else if (day === "Tue") { go_to_the_park(); } else if (day === "Thu") { go_ice_fishing(); } else if (day === "Fri" || day === "Sat") { if (day === bingo_day) { go_to_bingo(); go_dancing(); } } else if (day === "Sun") { 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).
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(); }
Chained Comparisons CoffeeScript borrows chained comparisons from Python — making it easy to test if a value falls within a certain range.
cholesterol: 127 healthy: 200 > cholesterol > 60
var cholesterol, healthy; cholesterol = 127; healthy = (200 > cholesterol) && (cholesterol > 60);
String and RegExp Interpolation A version of ECMAScript Harmony's proposed string interpolation is included in CoffeeScript. Simple variables can be included by marking them with a dollar sign.
author: "Wittgenstein" quote: "A picture is a fact. -- $author"
var author, quote; author = "Wittgenstein"; quote = "A picture is a fact. -- " + author;
And arbitrary expressions can be interpolated by using brackets ${ ... }
Interpolation works the same way within regular expressions.
sentence: "${ 22 / 7 } is a decent approximation of π" sep: "[.\\/\\- ]" dates: /\d+$sep\d+$sep\d+/g
var dates, sentence, sep; sentence = "" + (22 / 7) + " is a decent approximation of π"; sep = "[.\\/\\- ]"; dates = (new RegExp("\\d+" + sep + "\\d+" + sep + "\\d+", "g"));
Multiline Strings and Heredocs 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; 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...";
Heredocs can be used to hold formatted or indentation-sensitive text (or, if you just don't feel like escaping quotes and apostrophes). The indentation level that begins the heredoc is maintained throughout, so you can keep it all aligned with the body of your code.
html: ''' <strong> cup of coffeescript </strong> '''
var html; html = '<strong>\n cup of coffeescript\n</strong>';
Double-quoted heredocs, like double-quoted strings, allow interpolation.
CoffeeScript includes a simple build system similar to Make and Rake. Naturally, it's called Cake, and is used for the build and test tasks for the CoffeeScript language itself. Tasks are defined in a file named Cakefile, and can be invoked by running cake taskname from within the directory. To print a list of all the tasks, just run cake.
Task definitions are written in CoffeeScript, so you can put arbitrary code in your Cakefile. Define a task with a name, a long description, and the function to invoke when the task is run. Here's a hypothetical task that uses the Node.js API.
task 'test', 'run each of the unit tests', -> for test in test_files fs.readFile test, (err, code) -> eval coffee.compile code
task('test', 'run each of the unit tests', function() { var _a, _b, _c, _d, test; _a = []; _c = test_files; for (_b = 0, _d = _c.length; _b < _d; _b++) { test = _c[_b]; _a.push(fs.readFile(test, function(err, code) { return eval(coffee.compile(code)); })); } return _a; });
While it's not recommended for serious use, CoffeeScripts may be included directly within the browser using <script type="text/coffeescript"> tags. The source includes a compressed and minified version of the compiler (Download current version here, 43k when gzipped) as extras/coffee-script.js. Include this file on a page with inline CoffeeScript tags, and it will compile and evaluate them in order.
In fact, the little bit of glue script that runs "Try CoffeeScript" above, as well as jQuery for the menu, is implemented in just this way. View source and look at the bottom of the page to see the example. Including the script also gives you access to CoffeeScript.compile() so you can pop open Firebug and try compiling some strings.
The usual caveats about CoffeeScript apply — your inline scripts will run within a closure wrapper, so if you want to expose global variables or functions, attach them to the window object.
0.6.0 Trailing commas are now allowed, a-la Python. Static properties may be assigned directly within class definitions, using @property notation.
0.5.6 Interpolation can now be used within regular expressions and heredocs, as well as strings. Added the <- bind operator. Allowing assignment to half-expressions instead of special ||=-style operators. The arguments object is no longer automatically converted into an array. After requiring coffee-script, Node.js can now directly load .coffee files, thanks to registerExtension. Multiple splats can now be used in function calls, arrays, and pattern matching.
0.5.5 String interpolation, contributed by Stan Angeloff. Since --run has been the default since 0.5.3, updating --stdio and --eval to run by default, pass --compile as well if you'd like to print the result.
0.5.4 Bugfix that corrects the Node.js global constants __filename and __dirname. Tweaks for more flexible parsing of nested function literals and improperly-indented comments. Updates for the latest Node.js API.
0.5.3 CoffeeScript now has a syntax for defining classes. Many of the core components (Nodes, Lexer, Rewriter, Scope, Optparse) are using them. Cakefiles can use optparse.coffee to define options for tasks. --run is now the default flag for the coffee command, use --compile to save JavaScripts. Bugfix for an ambiguity between RegExp literals and chained divisions.
0.5.2
Added a compressed version of the compiler for inclusion in web pages as
extras/coffee-script.js. It'll automatically run any script tags
with type text/coffeescript for you. Added a --stdio option
to the coffee command, for piped-in compiles.
0.5.1 Improvements to null soaking with the existential operator, including soaks on indexed properties. Added conditions to while loops, so you can use them as filters with when, in the same manner as comprehensions.
0.5.0 CoffeeScript 0.5.0 is a major release, While there are no language changes, the Ruby compiler has been removed in favor of a self-hosting compiler written in pure CoffeeScript.
0.3.2
@property is now a shorthand for this.property.
Switched the default JavaScript engine from Narwhal to Node.js. Pass
the --narwhal flag if you'd like to continue using it.
0.3.0
CoffeeScript 0.3 includes major syntax changes:
The function symbol was changed to
->, and the bound function symbol is now =>.
Parameter lists in function definitions must now be wrapped in parentheses.
Added property soaking, with the ?. operator.
Made parentheses optional, when invoking functions with arguments.
Removed the obsolete block literal syntax.
0.2.6 Added Python-style chained comparisons, the conditional existence operator ?=, and some examples from Beautiful Code. Bugfixes relating to statement-to-expression conversion, arguments-to-array conversion, and the TextMate syntax highlighter.
0.2.5 The conditions in switch statements can now take multiple values at once — If any of them are true, the case will run. Added the long arrow ==>, which defines and immediately binds a function to this. While loops can now be used as expressions, in the same way that comprehensions can. Splats can be used within pattern matches to soak up the rest of an array.
0.2.4 Added ECMAScript Harmony style destructuring assignment, for dealing with extracting values from nested arrays and objects. Added indentation-sensitive heredocs for nicely formatted strings or chunks of code.
0.2.3 Axed the unsatisfactory ino keyword, replacing it with of for object comprehensions. They now look like: for prop, value of object.
0.2.2
When performing a comprehension over an object, use ino, instead
of in, which helps us generate smaller, more efficient code at
compile time.
Added :: as a shorthand for saying .prototype.
The "splat" symbol has been changed from a prefix asterisk *, to
a postfix ellipsis ...
Added JavaScript's in operator,
empty return statements, and empty while loops.
Constructor functions that start with capital letters now include a
safety check to make sure that the new instance of the object is returned.
The extends keyword now functions identically to goog.inherits
in Google's Closure Library.
0.2.1 Arguments objects are now converted into real arrays when referenced.
0.2.0 Major release. Significant whitespace. Better statement-to-expression conversion. Splats. Splice literals. Object comprehensions. Blocks. The existential operator. Many thanks to all the folks who posted issues, with special thanks to Liam O'Connor-Davis for whitespace and expression help.
0.1.6 Bugfix for running coffee --interactive and --run from outside of the CoffeeScript directory. Bugfix for nested function/if-statements.
0.1.5 Array slice literals and array comprehensions can now both take Ruby-style ranges to specify the start and end. JavaScript variable declaration is now pushed up to the top of the scope, making all assignment statements into expressions. You can use \ to escape newlines. The coffee-script command is now called coffee.
0.1.4 The official CoffeeScript extension is now .coffee instead of .cs, which properly belongs to C#. Due to popular demand, you can now also use = to assign. Unlike JavaScript, = can also be used within object literals, interchangeably with :. Made a grammatical fix for chained function calls like func(1)(2)(3)(4). Inheritance and super no longer use __proto__, so they should be IE-compatible now.
0.1.3 The coffee command now includes --interactive, which launches an interactive CoffeeScript session, and --run, which directly compiles and executes a script. Both options depend on a working installation of Narwhal. The aint keyword has been replaced by isnt, which goes together a little smoother with is. Quoted strings are now allowed as identifiers within object literals: eg. {"5+5": 10}. All assignment operators now use a colon: +:, -:, *:, etc.
0.1.2 Fixed a bug with calling super() through more than one level of inheritance, with the re-addition of the extends keyword. Added experimental Narwhal support (as a Tusk package), contributed by Tom Robinson, including bin/cs as a CoffeeScript REPL and interpreter. New --no-wrap option to suppress the safety function wrapper.
0.1.1 Added instanceof and typeof as operators.
0.1.0 Initial CoffeeScript release.