Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Fetching contributors…

Cannot retrieve contributors at this time

3531 lines (3054 sloc) 170.668 kb
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=UTF-8" />
<title>CoffeeScript</title>
<link rel="canonical" href="http://coffeescript.org" />
<link rel="stylesheet" type="text/css" href="documentation/css/docs.css" />
<link rel="stylesheet" type="text/css" href="documentation/css/tomorrow.css" />
<link rel="shortcut icon" href="documentation/images/favicon.ico" />
</head>
<body>
<div id="fadeout"></div>
<div id="flybar">
<a id="logo" href="#top"><img src="documentation/images/logo.png" width="225" height="39" alt="CoffeeScript" /></a>
<div class="navigation toc">
<div class="button">
Table of Contents
</div>
<div class="contents menu">
<a href="#overview">Overview</a>
<a href="#installation">Installation</a>
<a href="#usage">Usage</a>
<a href="#literate">Literate CoffeeScript</a>
<a href="#language">Language Reference</a>
<a href="#literals">Literals: Functions, Objects and Arrays</a>
<a href="#lexical-scope">Lexical Scoping and Variable Safety</a>
<a href="#conditionals">If, Else, Unless, and Conditional Assignment</a>
<a href="#splats">Splats...</a>
<a href="#loops">Loops and Comprehensions</a>
<a href="#slices">Array Slicing and Splicing</a>
<a href="#expressions">Everything is an Expression</a>
<a href="#operators">Operators and Aliases</a>
<a href="#classes">Classes, Inheritance, and Super</a>
<a href="#destructuring">Destructuring Assignment</a>
<a href="#fat-arrow">Function Binding</a>
<a href="#embedded">Embedded JavaScript</a>
<a href="#switch">Switch and Try/Catch</a>
<a href="#comparisons">Chained Comparisons</a>
<a href="#strings">String Interpolation, Block Strings, and Block Comments</a>
<a href="#regexes">Block Regular Expressions</a>
<a href="#cake">Cake, and Cakefiles</a>
<a href="#source-maps">Source Maps</a>
<a href="#scripts">"text/coffeescript" Script Tags</a>
<a href="#resources">Books, Screencasts, Examples and Resources</a>
<a href="#changelog">Change Log</a>
</div>
</div>
<div class="navigation try">
<div class="button">
Try CoffeeScript
<div class="repl_bridge"></div>
</div>
<div class="contents repl_wrapper">
<div class="code">
<div class="screenshadow tl"></div>
<div class="screenshadow tr"></div>
<div class="screenshadow bl"></div>
<div class="screenshadow br"></div>
<div id="repl_source_wrap">
<textarea id="repl_source" rows="100" spellcheck="false">alert "Hello CoffeeScript!"</textarea>
</div>
<div id="repl_results_wrap"><pre id="repl_results"></pre></div>
<div class="minibutton dark run" title="Ctrl-Enter">Run</div>
<a class="minibutton permalink" id="repl_permalink">Link</a>
<br class="clear" />
</div>
</div>
</div>
<div class="navigation annotated">
<div class="button">
Annotated Source
</div>
<div class="contents menu">
<a href="documentation/docs/grammar.html">Grammar Rules &mdash; src/grammar</a>
<a href="documentation/docs/lexer.html">Lexing Tokens &mdash; src/lexer</a>
<a href="documentation/docs/rewriter.html">The Rewriter &mdash; src/rewriter</a>
<a href="documentation/docs/nodes.html">The Syntax Tree &mdash; src/nodes</a>
<a href="documentation/docs/scope.html">Lexical Scope &mdash; src/scope</a>
<a href="documentation/docs/helpers.html">Helpers &amp; Utility Functions &mdash; src/helpers</a>
<a href="documentation/docs/coffee-script.html">The CoffeeScript Module &mdash; src/coffee-script</a>
<a href="documentation/docs/cake.html">Cake &amp; Cakefiles &mdash; src/cake</a>
<a href="documentation/docs/command.html">"coffee" Command-Line Utility &mdash; src/command</a>
<a href="documentation/docs/optparse.html">Option Parsing &mdash; src/optparse</a>
<a href="documentation/docs/repl.html">Interactive REPL &mdash; src/repl</a>
<a href="documentation/docs/sourcemap.html">Source Maps &mdash; src/sourcemap</a>
</div>
</div>
</div>
<div class="container">
<span class="bookmark" id="top"></span>
<p>
<b>CoffeeScript is a little language that compiles into JavaScript.</b>
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.
</p>
<p>
The golden rule of CoffeeScript is: <i>"It's just JavaScript"</i>. The code
compiles one-to-one into the equivalent JS, and there is
no interpretation at runtime. You can use any existing JavaScript library
seamlessly from CoffeeScript (and vice-versa). The compiled output is
readable and pretty-printed, will work in every JavaScript runtime, and tends
to run as fast or faster than the equivalent handwritten JavaScript.
</p>
<p>
<b>Latest Version:</b>
<a href="http://github.com/jashkenas/coffeescript/tarball/1.8.0">1.8.0</a>
</p>
<pre>npm install -g coffee-script</pre>
<h2>
<span id="overview" class="bookmark"></span>
Overview
</h2>
<p><i>CoffeeScript on the left, compiled JavaScript output on the right.</i></p>
<div class='code'><pre><code><span class="comment"># Assignment:</span>
number = <span class="number">42</span>
opposite = <span class="literal">true</span>
<span class="comment"># Conditions:</span>
number = -<span class="number">42</span> <span class="keyword">if</span> opposite
<span class="comment"># Functions:</span>
<span class="function"><span class="title">square</span> = <span class="params">(x)</span> -&gt;</span> x * x
<span class="comment"># Arrays:</span>
list = [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>]
<span class="comment"># Objects:</span>
math =
<span class="attribute">root</span>: Math.sqrt
<span class="attribute">square</span>: square
<span class="attribute">cube</span>: <span class="function"><span class="params">(x)</span> -&gt;</span> x * square x
<span class="comment"># Splats:</span>
<span class="function"><span class="title">race</span> = <span class="params">(winner, runners...)</span> -&gt;</span>
<span class="built_in">print</span> winner, runners
<span class="comment"># Existence:</span>
alert <span class="string">"I knew it!"</span> <span class="keyword">if</span> elvis?
<span class="comment"># Array comprehensions:</span>
cubes = (math.cube num <span class="keyword">for</span> num <span class="keyword">in</span> list)
</code></pre><pre><code><span class="keyword">var</span> cubes, list, math, num, number, opposite, race, square,
__slice = [].slice;
number = <span class="number">42</span>;
opposite = <span class="literal">true</span>;
<span class="keyword">if</span> (opposite) {
number = -<span class="number">42</span>;
}
square = <span class="function"><span class="keyword">function</span><span class="params">(x)</span> {</span>
<span class="keyword">return</span> x * x;
};
list = [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>];
math = {
root: <span class="built_in">Math</span>.sqrt,
square: square,
cube: <span class="function"><span class="keyword">function</span><span class="params">(x)</span> {</span>
<span class="keyword">return</span> x * square(x);
}
};
race = <span class="function"><span class="keyword">function</span><span class="params">()</span> {</span>
<span class="keyword">var</span> runners, winner;
winner = <span class="built_in">arguments</span>[<span class="number">0</span>], runners = <span class="number">2</span> &lt;= <span class="built_in">arguments</span>.length ? __slice.call(<span class="built_in">arguments</span>, <span class="number">1</span>) : [];
<span class="keyword">return</span> print(winner, runners);
};
<span class="keyword">if</span> (<span class="keyword">typeof</span> elvis !== <span class="string">"undefined"</span> &amp;&amp; elvis !== <span class="literal">null</span>) {
alert(<span class="string">"I knew it!"</span>);
}
cubes = (<span class="function"><span class="keyword">function</span><span class="params">()</span> {</span>
<span class="keyword">var</span> _i, _len, _results;
_results = [];
<span class="keyword">for</span> (_i = <span class="number">0</span>, _len = list.length; _i &lt; _len; _i++) {
num = list[_i];
_results.push(math.cube(num));
}
<span class="keyword">return</span> _results;
})();
</code></pre><script>window.example1 = "# Assignment:\nnumber = 42\nopposite = true\n\n# Conditions:\nnumber = -42 if opposite\n\n# Functions:\nsquare = (x) -> x * x\n\n# Arrays:\nlist = [1, 2, 3, 4, 5]\n\n# Objects:\nmath =\n root: Math.sqrt\n square: square\n cube: (x) -> x * square x\n\n# Splats:\nrace = (winner, runners...) ->\n print winner, runners\n\n# Existence:\nalert \"I knew it!\" if elvis?\n\n# Array comprehensions:\ncubes = (math.cube num for num in list)\n"</script><div class='minibutton ok' onclick='javascript: var cubes, list, math, num, number, opposite, race, square,
__slice = [].slice;
number = 42;
opposite = true;
if (opposite) {
number = -42;
}
square = function(x) {
return x * x;
};
list = [1, 2, 3, 4, 5];
math = {
root: Math.sqrt,
square: square,
cube: function(x) {
return x * square(x);
}
};
race = function() {
var runners, winner;
winner = arguments[0], runners = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
return print(winner, runners);
};
if (typeof elvis !== "undefined" && elvis !== null) {
alert("I knew it!");
}
cubes = (function() {
var _i, _len, _results;
_results = [];
for (_i = 0, _len = list.length; _i < _len; _i++) {
num = list[_i];
_results.push(math.cube(num));
}
return _results;
})();
;alert(cubes);'>run: cubes</div><br class='clear' /></div>
<h2>
<span id="installation" class="bookmark"></span>
Installation
</h2>
<p>
The CoffeeScript compiler is itself
<a href="documentation/docs/grammar.html">written in CoffeeScript</a>,
using the <a href="http://jison.org">Jison parser generator</a>. The
command-line version of <tt>coffee</tt> is available as a
<a href="http://nodejs.org/">Node.js</a> utility. The
<a href="extras/coffee-script.js">core compiler</a> however, does not
depend on Node, and can be run in any JavaScript environment, or in the
browser (see "Try CoffeeScript", above).
</p>
<p>
To install, first make sure you have a working copy of the latest stable version of
<a href="http://nodejs.org/">Node.js</a>, and <a href="http://npmjs.org">npm</a>
(the Node Package Manager). You can then install CoffeeScript globally with npm:
</p>
<pre>
npm install -g coffee-script</pre>
<p>
When you need CoffeeScript as a dependency, install it locally:
</p>
<pre>
npm install --save coffee-script</pre>
<p>
If you'd prefer to install the latest <b>master</b> version of CoffeeScript, you
can clone the CoffeeScript
<a href="http://github.com/jashkenas/coffeescript">source repository</a>
from GitHub, or download
<a href="http://github.com/jashkenas/coffeescript/tarball/master">the source</a> directly.
To install the latest master CoffeeScript compiler with npm:
</p>
<pre>
npm install -g jashkenas/coffeescript</pre>
<p>
Or, if you want to install to <tt>/usr/local</tt>, and don't want to use
npm to manage it, open the <tt>coffee-script</tt> directory and run:
</p>
<pre>
sudo bin/cake install</pre>
<h2>
<span id="usage" class="bookmark"></span>
Usage
</h2>
<p>
Once installed, you should have access to the <tt>coffee</tt> command,
which can execute scripts, compile <tt>.coffee</tt> files into <tt>.js</tt>,
and provide an interactive REPL. The <tt>coffee</tt> command takes the
following options:
</p>
<table>
<tr>
<td><code>-c, --compile</code></td>
<td>
Compile a <tt>.coffee</tt> script into a <tt>.js</tt> JavaScript file
of the same name.
</td>
</tr>
<tr>
<td><code>-m, --map</code></td>
<td>
Generate source maps alongside the compiled JavaScript files. Adds
<tt>sourceMappingURL</tt> directives to the JavaScript as well.
</td>
</tr>
<tr>
<td width="25%"><code>-i, --interactive</code></td>
<td>
Launch an interactive CoffeeScript session to try short snippets.
Identical to calling <tt>coffee</tt> with no arguments.
</td>
</tr>
<tr>
<td><code>-o, --output [DIR]</code></td>
<td>
Write out all compiled JavaScript files into the specified directory.
Use in conjunction with <tt>--compile</tt> or <tt>--watch</tt>.
</td>
</tr>
<tr>
<td><code>-j, --join [FILE]</code></td>
<td>
Before compiling, concatenate all scripts together in the order they
were passed, and write them into the specified file.
Useful for building large projects.
</td>
</tr>
<tr>
<td><code>-w, --watch</code></td>
<td>
Watch files for changes, rerunning the specified command when any
file is updated.
</td>
</tr>
<tr>
<td><code>-p, --print</code></td>
<td>
Instead of writing out the JavaScript as a file, print it
directly to <b>stdout</b>.
</td>
</tr>
<tr>
<td><code>-s, --stdio</code></td>
<td>
Pipe in CoffeeScript to STDIN and get back JavaScript over STDOUT.
Good for use with processes written in other languages. An example:<br />
<tt>cat src/cake.coffee | coffee -sc</tt>
</td>
</tr>
<tr>
<td><code>-l, --literate</code></td>
<td>
Parses the code as Literate CoffeeScript. You only need to specify
this when passing in code directly over <b>stdio</b>, or using some sort
of extension-less file name.
</td>
</tr>
<tr>
<td><code>-e, --eval</code></td>
<td>
Compile and print a little snippet of CoffeeScript directly from the
command line. For example:<br /><tt>coffee -e "console.log num for num in [10..1]"</tt>
</td>
</tr>
<tr>
<td><code>-b, --bare</code></td>
<td>
Compile the JavaScript without the
<a href="#lexical-scope">top-level function safety wrapper</a>.
</td>
</tr>
<tr>
<td><code>-t, --tokens</code></td>
<td>
Instead of parsing the CoffeeScript, just lex it, and print out the
token stream: <tt>[IDENTIFIER square] [ASSIGN =] [PARAM_START (]</tt> ...
</td>
</tr>
<tr>
<td><code>-n, --nodes</code></td>
<td>
Instead of compiling the CoffeeScript, just lex and parse it, and print
out the parse tree:
<pre class="no_bar">
Expressions
Assign
Value "square"
Code "x"
Op *
Value "x"
Value "x"</pre>
</td>
</tr>
<tr>
<td><code>--nodejs</code></td>
<td>
The <tt>node</tt> executable has some useful options you can set,
such as<br /> <tt>--debug</tt>, <tt>--debug-brk</tt>, <tt>--max-stack-size</tt>,
and <tt>--expose-gc</tt>. Use this flag to forward options directly to Node.js.
To pass multiple flags, use <tt>--nodejs</tt> multiple times.
</td>
</tr>
</table>
<p>
<b>Examples:</b>
</p>
<ul>
<li>
Compile a directory tree of <tt>.coffee</tt> files in <tt>src</tt> into a parallel
tree of <tt>.js</tt> files in <tt>lib</tt>:<br />
<tt>coffee --compile --output lib/ src/</tt>
</li>
<li>
Watch a file for changes, and recompile it every time the file is saved:<br />
<tt>coffee --watch --compile experimental.coffee</tt>
</li>
<li>
Concatenate a list of files into a single script:<br />
<tt>coffee --join project.js --compile src/*.coffee</tt>
</li>
<li>
Print out the compiled JS from a one-liner:<br />
<tt>coffee -bpe "alert i for i in [0..10]"</tt>
</li>
<li>
All together now, watch and recompile an entire project as you work on it:<br />
<tt>coffee -o lib/ -cw src/</tt>
</li>
<li>
Start the CoffeeScript REPL (<tt>Ctrl-D</tt> to exit, <tt>Ctrl-V</tt>for multi-line):<br />
<tt>coffee</tt>
</li>
</ul>
<h2>
<span id="literate" class="bookmark"></span>
Literate CoffeeScript
</h2>
<p>
Besides being used as an ordinary programming language, CoffeeScript may
also be written in "literate" mode. If you name your file with a
<tt>.litcoffee</tt> extension, you can write it as a Markdown document &mdash;
a document that also happens to be executable CoffeeScript code. The compiler
will treat any indented blocks (Markdown's way of indicating source code)
as code, and ignore the rest as comments.
</p>
<p>
Just for kicks, a little bit of the compiler is currently implemented in this fashion:
See it
<a href="https://gist.github.com/jashkenas/3fc3c1a8b1009c00d9df">as a document</a>,
<a href="https://raw.github.com/jashkenas/coffeescript/master/src/scope.litcoffee">raw</a>,
and <a href="http://cl.ly/LxEu">properly highlighted in a text editor</a>.
</p>
<p>
I'm fairly excited about this direction for the language, and am looking
forward to writing (and more importantly, reading) more programs in this style.
More information about Literate CoffeeScript, including an
<a href="https://github.com/jashkenas/journo">example program</a>,
are <a href="http://ashkenas.com/literate-coffeescript">available in this blog post</a>.
</p>
<h2>
<span id="language" class="bookmark"></span>
Language Reference
</h2>
<p>
<i>
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.
</i>
</p>
<p>
<i>
Many of the examples can be run (where it makes sense) by pressing the <b>run</b>
button on the right, and can be loaded into the "Try CoffeeScript"
console by pressing the <b>load</b> button on the left.
</i>
<p>
First, the basics: CoffeeScript uses significant whitespace to delimit blocks of code.
You don't need to use semicolons <tt>;</tt> to terminate expressions,
ending the line will do just as well (although semicolons can still
be used to fit multiple expressions onto a single line).
Instead of using curly braces
<tt>{ }</tt> to surround blocks of code in <a href="#literals">functions</a>,
<a href="#conditionals">if-statements</a>,
<a href="#switch">switch</a>, and <a href="#try">try/catch</a>,
use indentation.
</p>
<p>
You don't need to use parentheses to invoke a function if you're passing
arguments. The implicit call wraps forward to the end of the line or block expression.<br />
<tt>console.log sys.inspect object</tt> &rarr; <tt>console.log(sys.inspect(object));</tt>
</p>
<p>
<span id="literals" class="bookmark"></span>
<b class="header">Functions</b>
Functions are defined by an optional list of parameters in parentheses,
an arrow, and the function body. The empty function looks like this:
<tt>-></tt>
</p>
<div class='code'><pre><code><span class="function"><span class="title">square</span> = <span class="params">(x)</span> -&gt;</span> x * x
<span class="function"><span class="title">cube</span> = <span class="params">(x)</span> -&gt;</span> square(x) * x
</code></pre><pre><code><span class="keyword">var</span> cube, square;
square = <span class="function"><span class="keyword">function</span><span class="params">(x)</span> {</span>
<span class="keyword">return</span> x * x;
};
cube = <span class="function"><span class="keyword">function</span><span class="params">(x)</span> {</span>
<span class="keyword">return</span> square(x) * x;
};
</code></pre><script>window.example2 = "square = (x) -> x * x\ncube = (x) -> square(x) * x\n"</script><div class='minibutton load' onclick='javascript: loadConsole(example2);'>load</div><div class='minibutton ok' onclick='javascript: var cube, square;
square = function(x) {
return x * x;
};
cube = function(x) {
return square(x) * x;
};
;alert(cube(5));'>run: cube(5)</div><br class='clear' /></div>
<p>
Functions may also have default values for arguments, which will be used
if the incoming argument is missing (<tt>null</tt> or <tt>undefined</tt>).
</p>
<div class='code'><pre><code><span class="function"><span class="title">fill</span> = <span class="params">(container, liquid = <span class="string">"coffee"</span>)</span> -&gt;</span>
<span class="string">"Filling the <span class="subst">#{container}</span> with <span class="subst">#{liquid}</span>..."</span>
</code></pre><pre><code><span class="keyword">var</span> fill;
fill = <span class="function"><span class="keyword">function</span><span class="params">(container, liquid)</span> {</span>
<span class="keyword">if</span> (liquid == <span class="literal">null</span>) {
liquid = <span class="string">"coffee"</span>;
}
<span class="keyword">return</span> <span class="string">"Filling the "</span> + container + <span class="string">" with "</span> + liquid + <span class="string">"..."</span>;
};
</code></pre><script>window.example3 = "fill = (container, liquid = \"coffee\") ->\n \"Filling the #{container} with #{liquid}...\"\n\n\n\n\n\n\n"</script><div class='minibutton load' onclick='javascript: loadConsole(example3);'>load</div><div class='minibutton ok' onclick='javascript: var fill;
fill = function(container, liquid) {
if (liquid == null) {
liquid = "coffee";
}
return "Filling the " + container + " with " + liquid + "...";
};
;alert(fill("cup"));'>run: fill("cup")</div><br class='clear' /></div>
<p>
<span id="objects_and_arrays" class="bookmark"></span>
<b class="header">Objects and Arrays</b>
The CoffeeScript literals for objects and arrays look very similar to
their JavaScript cousins. When each property is listed on its own line,
the commas are optional. Objects may be created using indentation instead
of explicit braces, similar to <a href="http://yaml.org">YAML</a>.
</p>
<div class='code'><pre><code>song = [<span class="string">"do"</span>, <span class="string">"re"</span>, <span class="string">"mi"</span>, <span class="string">"fa"</span>, <span class="string">"so"</span>]
singers = {<span class="attribute">Jagger</span>: <span class="string">"Rock"</span>, <span class="attribute">Elvis</span>: <span class="string">"Roll"</span>}
bitlist = [
<span class="number">1</span>, <span class="number">0</span>, <span class="number">1</span>
<span class="number">0</span>, <span class="number">0</span>, <span class="number">1</span>
<span class="number">1</span>, <span class="number">1</span>, <span class="number">0</span>
]
kids =
<span class="attribute">brother</span>:
<span class="attribute">name</span>: <span class="string">"Max"</span>
<span class="attribute">age</span>: <span class="number">11</span>
<span class="attribute">sister</span>:
<span class="attribute">name</span>: <span class="string">"Ida"</span>
<span class="attribute">age</span>: <span class="number">9</span>
</code></pre><pre><code><span class="keyword">var</span> bitlist, kids, singers, song;
song = [<span class="string">"do"</span>, <span class="string">"re"</span>, <span class="string">"mi"</span>, <span class="string">"fa"</span>, <span class="string">"so"</span>];
singers = {
Jagger: <span class="string">"Rock"</span>,
Elvis: <span class="string">"Roll"</span>
};
bitlist = [<span class="number">1</span>, <span class="number">0</span>, <span class="number">1</span>, <span class="number">0</span>, <span class="number">0</span>, <span class="number">1</span>, <span class="number">1</span>, <span class="number">1</span>, <span class="number">0</span>];
kids = {
brother: {
name: <span class="string">"Max"</span>,
age: <span class="number">11</span>
},
sister: {
name: <span class="string">"Ida"</span>,
age: <span class="number">9</span>
}
};
</code></pre><script>window.example4 = "song = [\"do\", \"re\", \"mi\", \"fa\", \"so\"]\n\nsingers = {Jagger: \"Rock\", Elvis: \"Roll\"}\n\nbitlist = [\n 1, 0, 1\n 0, 0, 1\n 1, 1, 0\n]\n\nkids =\n brother:\n name: \"Max\"\n age: 11\n sister:\n name: \"Ida\"\n age: 9\n\n\n"</script><div class='minibutton load' onclick='javascript: loadConsole(example4);'>load</div><div class='minibutton ok' onclick='javascript: var bitlist, kids, singers, song;
song = ["do", "re", "mi", "fa", "so"];
singers = {
Jagger: "Rock",
Elvis: "Roll"
};
bitlist = [1, 0, 1, 0, 0, 1, 1, 1, 0];
kids = {
brother: {
name: "Max",
age: 11
},
sister: {
name: "Ida",
age: 9
}
};
;alert(song.join(" ... "));'>run: song.join(" ... ")</div><br class='clear' /></div>
<p>
In JavaScript, you can't use reserved words, like <tt>class</tt>, as properties
of an object, without quoting them as strings. CoffeeScript notices reserved words
used as keys in objects and quotes them for you, so you don't have to worry
about it (say, when using jQuery).
</p>
<div class='code'><pre><code>$('.account').attr class: 'active'
log object.class
</code></pre><pre><code>$(<span class="string">'.account'</span>).attr({
<span class="string">"class"</span>: <span class="string">'active'</span>
});
log(object[<span class="string">"class"</span>]);
</code></pre><script>window.example5 = "$('.account').attr class: 'active'\n\nlog object.class\n\n\n"</script><div class='minibutton load' onclick='javascript: loadConsole(example5);'>load</div><br class='clear' /></div>
<p>
<span id="lexical-scope" class="bookmark"></span>
<b class="header">Lexical Scoping and Variable Safety</b>
The CoffeeScript compiler takes care to make sure that all of your variables
are properly declared within lexical scope &mdash; you never need to write
<tt>var</tt> yourself.
</p>
<div class='code'><pre><code>outer = <span class="number">1</span>
<span class="function"><span class="title">changeNumbers</span> = -&gt;</span>
inner = -<span class="number">1</span>
outer = <span class="number">10</span>
inner = changeNumbers()</code></pre><pre><code><span class="keyword">var</span> changeNumbers, inner, outer;
outer = <span class="number">1</span>;
changeNumbers = <span class="function"><span class="keyword">function</span><span class="params">()</span> {</span>
<span class="keyword">var</span> inner;
inner = -<span class="number">1</span>;
<span class="keyword">return</span> outer = <span class="number">10</span>;
};
inner = changeNumbers();
</code></pre><script>window.example6 = "outer = 1\nchangeNumbers = ->\n inner = -1\n outer = 10\ninner = changeNumbers()"</script><div class='minibutton load' onclick='javascript: loadConsole(example6);'>load</div><div class='minibutton ok' onclick='javascript: var changeNumbers, inner, outer;
outer = 1;
changeNumbers = function() {
var inner;
inner = -1;
return outer = 10;
};
inner = changeNumbers();
;alert(inner);'>run: inner</div><br class='clear' /></div>
<p>
Notice how all of the variable declarations have been pushed up to
the top of the closest scope, the first time they appear.
<b>outer</b> is not redeclared within the inner function, because it's
already in scope; <b>inner</b> 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.
</p>
<p>
This behavior is effectively identical to Ruby's scope for local variables.
Because you don't have direct access to the <tt>var</tt> 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.
</p>
<p>
Although suppressed within this documentation for clarity, all
CoffeeScript output is wrapped in an anonymous function:
<tt>(function(){ ... })();</tt> This safety wrapper, combined with the
automatic generation of the <tt>var</tt> keyword, make it exceedingly difficult
to pollute the global namespace by accident.
</p>
<p>
If you'd like to create top-level variables for other scripts to use,
attach them as properties on <b>window</b>, or on the <b>exports</b>
object in CommonJS. The <b>existential operator</b> (covered below), gives you a
reliable way to figure out where to add them; if you're targeting both
CommonJS and the browser: <tt>exports ? this</tt>
</p>
<p>
<span id="conditionals" class="bookmark"></span>
<b class="header">If, Else, Unless, and Conditional Assignment</b>
<b>If/else</b> 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 <tt>if</tt> or <tt>unless</tt> at the end.
</p>
<p>
CoffeeScript can compile <b>if</b> statements into JavaScript expressions,
using the ternary operator when possible, and closure wrapping otherwise. There
is no explicit ternary statement in CoffeeScript &mdash; you simply use
a regular <b>if</b> statement on a single line.
</p>
<div class='code'><pre><code>mood = greatlyImproved <span class="keyword">if</span> singing
<span class="keyword">if</span> happy <span class="keyword">and</span> knowsIt
clapsHands()
chaChaCha()
<span class="keyword">else</span>
showIt()
date = <span class="keyword">if</span> friday <span class="keyword">then</span> sue <span class="keyword">else</span> jill
</code></pre><pre><code><span class="keyword">var</span> date, mood;
<span class="keyword">if</span> (singing) {
mood = greatlyImproved;
}
<span class="keyword">if</span> (happy &amp;&amp; knowsIt) {
clapsHands();
chaChaCha();
} <span class="keyword">else</span> {
showIt();
}
date = friday ? sue : jill;
</code></pre><script>window.example7 = "mood = greatlyImproved if singing\n\nif happy and knowsIt\n clapsHands()\n chaChaCha()\nelse\n showIt()\n\ndate = if friday then sue else jill\n\n\n\n"</script><div class='minibutton load' onclick='javascript: loadConsole(example7);'>load</div><br class='clear' /></div>
<p>
<span id="splats" class="bookmark"></span>
<b class="header">Splats...</b>
The JavaScript <b>arguments object</b> is a useful way to work with
functions that accept variable numbers of arguments. CoffeeScript provides
splats <tt>...</tt>, both for function definition as well as invocation,
making variable numbers of arguments a little bit more palatable.
</p>
<div class='code'><pre><code>gold = silver = rest = <span class="string">"unknown"</span>
<span class="function"><span class="title">awardMedals</span> = <span class="params">(first, second, others...)</span> -&gt;</span>
gold = first
silver = second
rest = others
contenders = [
<span class="string">"Michael Phelps"</span>
<span class="string">"Liu Xiang"</span>
<span class="string">"Yao Ming"</span>
<span class="string">"Allyson Felix"</span>
<span class="string">"Shawn Johnson"</span>
<span class="string">"Roman Sebrle"</span>
<span class="string">"Guo Jingjing"</span>
<span class="string">"Tyson Gay"</span>
<span class="string">"Asafa Powell"</span>
<span class="string">"Usain Bolt"</span>
]
awardMedals contenders...
alert <span class="string">"Gold: "</span> + gold
alert <span class="string">"Silver: "</span> + silver
alert <span class="string">"The Field: "</span> + rest
</code></pre><pre><code><span class="keyword">var</span> awardMedals, contenders, gold, rest, silver,
__slice = [].slice;
gold = silver = rest = <span class="string">"unknown"</span>;
awardMedals = <span class="function"><span class="keyword">function</span><span class="params">()</span> {</span>
<span class="keyword">var</span> first, others, second;
first = <span class="built_in">arguments</span>[<span class="number">0</span>], second = <span class="built_in">arguments</span>[<span class="number">1</span>], others = <span class="number">3</span> &lt;= <span class="built_in">arguments</span>.length ? __slice.call(<span class="built_in">arguments</span>, <span class="number">2</span>) : [];
gold = first;
silver = second;
<span class="keyword">return</span> rest = others;
};
contenders = [<span class="string">"Michael Phelps"</span>, <span class="string">"Liu Xiang"</span>, <span class="string">"Yao Ming"</span>, <span class="string">"Allyson Felix"</span>, <span class="string">"Shawn Johnson"</span>, <span class="string">"Roman Sebrle"</span>, <span class="string">"Guo Jingjing"</span>, <span class="string">"Tyson Gay"</span>, <span class="string">"Asafa Powell"</span>, <span class="string">"Usain Bolt"</span>];
awardMedals.apply(<span class="literal">null</span>, contenders);
alert(<span class="string">"Gold: "</span> + gold);
alert(<span class="string">"Silver: "</span> + silver);
alert(<span class="string">"The Field: "</span> + rest);
</code></pre><script>window.example8 = "gold = silver = rest = \"unknown\"\n\nawardMedals = (first, second, others...) ->\n gold = first\n silver = second\n rest = others\n\ncontenders = [\n \"Michael Phelps\"\n \"Liu Xiang\"\n \"Yao Ming\"\n \"Allyson Felix\"\n \"Shawn Johnson\"\n \"Roman Sebrle\"\n \"Guo Jingjing\"\n \"Tyson Gay\"\n \"Asafa Powell\"\n \"Usain Bolt\"\n]\n\nawardMedals contenders...\n\nalert \"Gold: \" + gold\nalert \"Silver: \" + silver\nalert \"The Field: \" + rest\n\n\n"</script><div class='minibutton load' onclick='javascript: loadConsole(example8);'>load</div><div class='minibutton ok' onclick='javascript: var awardMedals, contenders, gold, rest, silver,
__slice = [].slice;
gold = silver = rest = "unknown";
awardMedals = function() {
var first, others, second;
first = arguments[0], second = arguments[1], others = 3 <= arguments.length ? __slice.call(arguments, 2) : [];
gold = first;
silver = second;
return rest = others;
};
contenders = ["Michael Phelps", "Liu Xiang", "Yao Ming", "Allyson Felix", "Shawn Johnson", "Roman Sebrle", "Guo Jingjing", "Tyson Gay", "Asafa Powell", "Usain Bolt"];
awardMedals.apply(null, contenders);
alert("Gold: " + gold);
alert("Silver: " + silver);
alert("The Field: " + rest);
;'>run</div><br class='clear' /></div>
<p>
<span id="loops" class="bookmark"></span>
<b class="header">Loops and Comprehensions</b>
Most of the loops you'll write in CoffeeScript will be <b>comprehensions</b>
over arrays, objects, and ranges. Comprehensions replace (and compile into)
<b>for</b> 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.
</p>
<div class='code'><pre><code><span class="comment"># Eat lunch.</span>
eat food <span class="keyword">for</span> food <span class="keyword">in</span> [<span class="string">'toast'</span>, <span class="string">'cheese'</span>, <span class="string">'wine'</span>]
<span class="comment"># Fine five course dining.</span>
courses = [<span class="string">'greens'</span>, <span class="string">'caviar'</span>, <span class="string">'truffles'</span>, <span class="string">'roast'</span>, <span class="string">'cake'</span>]
menu i + <span class="number">1</span>, dish <span class="keyword">for</span> dish, i <span class="keyword">in</span> courses
<span class="comment"># Health conscious meal.</span>
foods = [<span class="string">'broccoli'</span>, <span class="string">'spinach'</span>, <span class="string">'chocolate'</span>]
eat food <span class="keyword">for</span> food <span class="keyword">in</span> foods <span class="keyword">when</span> food <span class="keyword">isnt</span> <span class="string">'chocolate'</span>
</code></pre><pre><code><span class="keyword">var</span> courses, dish, food, foods, i, _i, _j, _k, _len, _len1, _len2, _ref;
_ref = [<span class="string">'toast'</span>, <span class="string">'cheese'</span>, <span class="string">'wine'</span>];
<span class="keyword">for</span> (_i = <span class="number">0</span>, _len = _ref.length; _i &lt; _len; _i++) {
food = _ref[_i];
eat(food);
}
courses = [<span class="string">'greens'</span>, <span class="string">'caviar'</span>, <span class="string">'truffles'</span>, <span class="string">'roast'</span>, <span class="string">'cake'</span>];
<span class="keyword">for</span> (i = _j = <span class="number">0</span>, _len1 = courses.length; _j &lt; _len1; i = ++_j) {
dish = courses[i];
menu(i + <span class="number">1</span>, dish);
}
foods = [<span class="string">'broccoli'</span>, <span class="string">'spinach'</span>, <span class="string">'chocolate'</span>];
<span class="keyword">for</span> (_k = <span class="number">0</span>, _len2 = foods.length; _k &lt; _len2; _k++) {
food = foods[_k];
<span class="keyword">if</span> (food !== <span class="string">'chocolate'</span>) {
eat(food);
}
}
</code></pre><script>window.example9 = "# Eat lunch.\neat food for food in ['toast', 'cheese', 'wine']\n\n# Fine five course dining.\ncourses = ['greens', 'caviar', 'truffles', 'roast', 'cake']\nmenu i + 1, dish for dish, i in courses\n\n# Health conscious meal.\nfoods = ['broccoli', 'spinach', 'chocolate']\neat food for food in foods when food isnt 'chocolate'\n"</script><div class='minibutton load' onclick='javascript: loadConsole(example9);'>load</div><br class='clear' /></div>
<p>
Comprehensions should be able to handle most places where you otherwise
would use a loop, <b>each</b>/<b>forEach</b>, <b>map</b>, or <b>select</b>/<b>filter</b>, for example:
<tt>shortNames = (name for name in list when name.length &lt; 5)</tt><br />
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.
</p>
<div class='code'><pre><code>countdown = (num <span class="keyword">for</span> num <span class="keyword">in</span> [<span class="number">10.</span><span class="number">.1</span>])
</code></pre><pre><code><span class="keyword">var</span> countdown, num;
countdown = (<span class="function"><span class="keyword">function</span><span class="params">()</span> {</span>
<span class="keyword">var</span> _i, _results;
_results = [];
<span class="keyword">for</span> (num = _i = <span class="number">10</span>; _i &gt;= <span class="number">1</span>; num = --_i) {
_results.push(num);
}
<span class="keyword">return</span> _results;
})();
</code></pre><script>window.example10 = "countdown = (num for num in [10..1])\n\n"</script><div class='minibutton load' onclick='javascript: loadConsole(example10);'>load</div><div class='minibutton ok' onclick='javascript: var countdown, num;
countdown = (function() {
var _i, _results;
_results = [];
for (num = _i = 10; _i >= 1; num = --_i) {
_results.push(num);
}
return _results;
})();
;alert(countdown);'>run: countdown</div><br class='clear' /></div>
<p>
Note how because we are assigning the value of the comprehensions to a
variable in the example above, CoffeeScript is collecting the result of
each iteration into an array. Sometimes functions end with loops that are
intended to run only for their side-effects. Be careful that you're not
accidentally returning the results of the comprehension in these cases,
by adding a meaningful return value &mdash; like <tt>true</tt> &mdash; or <tt>null</tt>,
to the bottom of your function.
</p>
<p>
To step through a range comprehension in fixed-size chunks,
use <tt>by</tt>, for example:<br />
<tt>evens = (x for x in [0..10] by 2)</tt>
</p>
<p>
Comprehensions can also be used to iterate over the keys and values in
an object. Use <tt>of</tt> to signal comprehension over the properties of
an object instead of the values in an array.
</p>
<div class='code'><pre><code>yearsOld = <span class="attribute">max</span>: <span class="number">10</span>, <span class="attribute">ida</span>: <span class="number">9</span>, <span class="attribute">tim</span>: <span class="number">11</span>
ages = <span class="keyword">for</span> child, age <span class="keyword">of</span> yearsOld
<span class="string">"<span class="subst">#{child}</span> is <span class="subst">#{age}</span>"</span>
</code></pre><pre><code><span class="keyword">var</span> age, ages, child, yearsOld;
yearsOld = {
max: <span class="number">10</span>,
ida: <span class="number">9</span>,
tim: <span class="number">11</span>
};
ages = (<span class="function"><span class="keyword">function</span><span class="params">()</span> {</span>
<span class="keyword">var</span> _results;
_results = [];
<span class="keyword">for</span> (child <span class="keyword">in</span> yearsOld) {
age = yearsOld[child];
_results.push(<span class="string">""</span> + child + <span class="string">" is "</span> + age);
}
<span class="keyword">return</span> _results;
})();
</code></pre><script>window.example11 = "yearsOld = max: 10, ida: 9, tim: 11\n\nages = for child, age of yearsOld\n \"#{child} is #{age}\"\n"</script><div class='minibutton load' onclick='javascript: loadConsole(example11);'>load</div><div class='minibutton ok' onclick='javascript: var age, ages, child, yearsOld;
yearsOld = {
max: 10,
ida: 9,
tim: 11
};
ages = (function() {
var _results;
_results = [];
for (child in yearsOld) {
age = yearsOld[child];
_results.push("" + child + " is " + age);
}
return _results;
})();
;alert(ages.join(", "));'>run: ages.join(", ")</div><br class='clear' /></div>
<p>
If you would like to iterate over just the keys that are defined on the
object itself, by adding a <tt>hasOwnProperty</tt>
check to avoid properties that may be inherited from the prototype, use<br />
<tt>for own key, value of object</tt>
</p>
<p>
The only low-level loop that CoffeeScript provides is the <b>while</b> loop. The
main difference from JavaScript is that the <b>while</b> loop can be used
as an expression, returning an array containing the result of each iteration
through the loop.
</p>
<div class='code'><pre><code><span class="comment"># Econ 101</span>
<span class="keyword">if</span> <span class="keyword">this</span>.studyingEconomics
buy() <span class="keyword">while</span> supply &gt; demand
sell() <span class="keyword">until</span> supply &gt; demand
<span class="comment"># Nursery Rhyme</span>
num = <span class="number">6</span>
lyrics = <span class="keyword">while</span> num -= <span class="number">1</span>
<span class="string">"<span class="subst">#{num}</span> little monkeys, jumping on the bed.
One fell out and bumped his head."</span>
</code></pre><pre><code><span class="keyword">var</span> lyrics, num;
<span class="keyword">if</span> (<span class="keyword">this</span>.studyingEconomics) {
<span class="keyword">while</span> (supply &gt; demand) {
buy();
}
<span class="keyword">while</span> (!(supply &gt; demand)) {
sell();
}
}
num = <span class="number">6</span>;
lyrics = (<span class="function"><span class="keyword">function</span><span class="params">()</span> {</span>
<span class="keyword">var</span> _results;
_results = [];
<span class="keyword">while</span> (num -= <span class="number">1</span>) {
_results.push(<span class="string">""</span> + num + <span class="string">" little monkeys, jumping on the bed. One fell out and bumped his head."</span>);
}
<span class="keyword">return</span> _results;
})();
</code></pre><script>window.example12 = "# Econ 101\nif this.studyingEconomics\n buy() while supply > demand\n sell() until supply > demand\n\n# Nursery Rhyme\nnum = 6\nlyrics = while num -= 1\n \"#{num} little monkeys, jumping on the bed.\n One fell out and bumped his head.\"\n"</script><div class='minibutton load' onclick='javascript: loadConsole(example12);'>load</div><div class='minibutton ok' onclick='javascript: var lyrics, num;
if (this.studyingEconomics) {
while (supply > demand) {
buy();
}
while (!(supply > demand)) {
sell();
}
}
num = 6;
lyrics = (function() {
var _results;
_results = [];
while (num -= 1) {
_results.push("" + num + " little monkeys, jumping on the bed. One fell out and bumped his head.");
}
return _results;
})();
;alert(lyrics.join("
"));'>run: lyrics.join("
")</div><br class='clear' /></div>
<p>
For readability, the <b>until</b> keyword is equivalent to <tt>while not</tt>,
and the <b>loop</b> keyword is equivalent to <tt>while true</tt>.
</p>
<p>
When using a JavaScript loop to generate functions, it's common to insert
a closure wrapper in order to ensure that loop variables are closed over,
and all the generated functions don't just share the final values. CoffeeScript
provides the <tt>do</tt> keyword, which immediately invokes a passed function,
forwarding any arguments.
</p>
<div class='code'><pre><code><span class="keyword">for</span> filename <span class="keyword">in</span> list
<span class="keyword">do</span> <span class="function"><span class="params">(filename)</span> -&gt;</span>
fs.readFile filename, <span class="function"><span class="params">(err, contents)</span> -&gt;</span>
compile filename, contents.toString()</code></pre><pre><code><span class="keyword">var</span> filename, _fn, _i, _len;
_fn = <span class="function"><span class="keyword">function</span><span class="params">(filename)</span> {</span>
<span class="keyword">return</span> fs.readFile(filename, <span class="function"><span class="keyword">function</span><span class="params">(err, contents)</span> {</span>
<span class="keyword">return</span> compile(filename, contents.toString());
});
};
<span class="keyword">for</span> (_i = <span class="number">0</span>, _len = list.length; _i &lt; _len; _i++) {
filename = list[_i];
_fn(filename);
}
</code></pre><script>window.example13 = "for filename in list\n do (filename) ->\n fs.readFile filename, (err, contents) ->\n compile filename, contents.toString()"</script><div class='minibutton load' onclick='javascript: loadConsole(example13);'>load</div><br class='clear' /></div>
<p>
<span id="slices" class="bookmark"></span>
<b class="header">Array Slicing and Splicing with Ranges</b>
Ranges can also be used to extract slices of arrays.
With two dots (<tt>3..6</tt>), the range is inclusive (<tt>3, 4, 5, 6</tt>);
with three dots (<tt>3...6</tt>), the range excludes the end (<tt>3, 4, 5</tt>).
Slices indices have useful defaults. An omitted first index defaults to
zero and an omitted second index defaults to the size of the array.
</p>
<div class='code'><pre><code>numbers = [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>, <span class="number">6</span>, <span class="number">7</span>, <span class="number">8</span>, <span class="number">9</span>]
start = numbers[<span class="number">0.</span><span class="number">.2</span>]
middle = numbers[<span class="number">3.</span>..-<span class="number">2</span>]
end = numbers[-<span class="number">2.</span>.]
copy = numbers[..]
</code></pre><pre><code><span class="keyword">var</span> copy, end, middle, numbers, start;
numbers = [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>, <span class="number">6</span>, <span class="number">7</span>, <span class="number">8</span>, <span class="number">9</span>];
start = numbers.slice(<span class="number">0</span>, <span class="number">3</span>);
middle = numbers.slice(<span class="number">3</span>, -<span class="number">2</span>);
end = numbers.slice(-<span class="number">2</span>);
copy = numbers.slice(<span class="number">0</span>);
</code></pre><script>window.example14 = "numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]\n\nstart = numbers[0..2]\n\nmiddle = numbers[3...-2]\n\nend = numbers[-2..]\n\ncopy = numbers[..]\n"</script><div class='minibutton load' onclick='javascript: loadConsole(example14);'>load</div><div class='minibutton ok' onclick='javascript: var copy, end, middle, numbers, start;
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];
start = numbers.slice(0, 3);
middle = numbers.slice(3, -2);
end = numbers.slice(-2);
copy = numbers.slice(0);
;alert(middle);'>run: middle</div><br class='clear' /></div>
<p>
The same syntax can be used with assignment to replace a segment of an array
with new values, splicing it.
</p>
<div class='code'><pre><code>numbers = [<span class="number">0</span>, <span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>, <span class="number">6</span>, <span class="number">7</span>, <span class="number">8</span>, <span class="number">9</span>]
numbers[<span class="number">3.</span><span class="number">.6</span>] = [-<span class="number">3</span>, -<span class="number">4</span>, -<span class="number">5</span>, -<span class="number">6</span>]
</code></pre><pre><code><span class="keyword">var</span> numbers, _ref;
numbers = [<span class="number">0</span>, <span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>, <span class="number">6</span>, <span class="number">7</span>, <span class="number">8</span>, <span class="number">9</span>];
[].splice.apply(numbers, [<span class="number">3</span>, <span class="number">4</span>].concat(_ref = [-<span class="number">3</span>, -<span class="number">4</span>, -<span class="number">5</span>, -<span class="number">6</span>])), _ref;
</code></pre><script>window.example15 = "numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n\nnumbers[3..6] = [-3, -4, -5, -6]\n\n\n\n "</script><div class='minibutton load' onclick='javascript: loadConsole(example15);'>load</div><div class='minibutton ok' onclick='javascript: var numbers, _ref;
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
[].splice.apply(numbers, [3, 4].concat(_ref = [-3, -4, -5, -6])), _ref;
;alert(numbers);'>run: numbers</div><br class='clear' /></div>
<p>
Note that JavaScript strings are immutable, and can't be spliced.
</p>
<p>
<span id="expressions" class="bookmark"></span>
<b class="header">Everything is an Expression (at least, as much as possible)</b>
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 <tt>return</tt> gets
pushed down into each possible branch of execution in the function
below.
</p>
<div class='code'><pre><code><span class="function"><span class="title">grade</span> = <span class="params">(student)</span> -&gt;</span>
<span class="keyword">if</span> student.excellentWork
<span class="string">"A+"</span>
<span class="keyword">else</span> <span class="keyword">if</span> student.okayStuff
<span class="keyword">if</span> student.triedHard <span class="keyword">then</span> <span class="string">"B"</span> <span class="keyword">else</span> <span class="string">"B-"</span>
<span class="keyword">else</span>
<span class="string">"C"</span>
eldest = <span class="keyword">if</span> <span class="number">24</span> &gt; <span class="number">21</span> <span class="keyword">then</span> <span class="string">"Liz"</span> <span class="keyword">else</span> <span class="string">"Ike"</span></code></pre><pre><code><span class="keyword">var</span> eldest, grade;
grade = <span class="function"><span class="keyword">function</span><span class="params">(student)</span> {</span>
<span class="keyword">if</span> (student.excellentWork) {
<span class="keyword">return</span> <span class="string">"A+"</span>;
} <span class="keyword">else</span> <span class="keyword">if</span> (student.okayStuff) {
<span class="keyword">if</span> (student.triedHard) {
<span class="keyword">return</span> <span class="string">"B"</span>;
} <span class="keyword">else</span> {
<span class="keyword">return</span> <span class="string">"B-"</span>;
}
} <span class="keyword">else</span> {
<span class="keyword">return</span> <span class="string">"C"</span>;
}
};
eldest = <span class="number">24</span> &gt; <span class="number">21</span> ? <span class="string">"Liz"</span> : <span class="string">"Ike"</span>;
</code></pre><script>window.example16 = "grade = (student) ->\n if student.excellentWork\n \"A+\"\n else if student.okayStuff\n if student.triedHard then \"B\" else \"B-\"\n else\n \"C\"\n\neldest = if 24 > 21 then \"Liz\" else \"Ike\""</script><div class='minibutton load' onclick='javascript: loadConsole(example16);'>load</div><div class='minibutton ok' onclick='javascript: var eldest, grade;
grade = function(student) {
if (student.excellentWork) {
return "A+";
} else if (student.okayStuff) {
if (student.triedHard) {
return "B";
} else {
return "B-";
}
} else {
return "C";
}
};
eldest = 24 > 21 ? "Liz" : "Ike";
;alert(eldest);'>run: eldest</div><br class='clear' /></div>
<p>
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 (<tt>return value</tt>), when you know that you're done.
</p>
<p>
Because variable declarations occur at the top of scope, assignment can
be used within expressions, even for variables that haven't been seen before:
</p>
<div class='code'><pre><code>six = (one = <span class="number">1</span>) + (two = <span class="number">2</span>) + (three = <span class="number">3</span>)
</code></pre><pre><code><span class="keyword">var</span> one, six, three, two;
six = (one = <span class="number">1</span>) + (two = <span class="number">2</span>) + (three = <span class="number">3</span>);
</code></pre><script>window.example17 = "six = (one = 1) + (two = 2) + (three = 3)\n\n\n"</script><div class='minibutton load' onclick='javascript: loadConsole(example17);'>load</div><div class='minibutton ok' onclick='javascript: var one, six, three, two;
six = (one = 1) + (two = 2) + (three = 3);
;alert(six);'>run: six</div><br class='clear' /></div>
<p>
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:
</p>
<div class='code'><pre><code><span class="comment"># The first ten global properties.</span>
globals = (name <span class="keyword">for</span> name <span class="keyword">of</span> <span class="built_in">window</span>)[<span class="number">0.</span>.<span class="number">.10</span>]</code></pre><pre><code><span class="keyword">var</span> globals, name;
globals = ((<span class="function"><span class="keyword">function</span><span class="params">()</span> {</span>
<span class="keyword">var</span> _results;
_results = [];
<span class="keyword">for</span> (name <span class="keyword">in</span> window) {
_results.push(name);
}
<span class="keyword">return</span> _results;
})()).slice(<span class="number">0</span>, <span class="number">10</span>);
</code></pre><script>window.example18 = "# The first ten global properties.\n\nglobals = (name for name of window)[0...10]"</script><div class='minibutton load' onclick='javascript: loadConsole(example18);'>load</div><div class='minibutton ok' onclick='javascript: var globals, name;
globals = ((function() {
var _results;
_results = [];
for (name in window) {
_results.push(name);
}
return _results;
})()).slice(0, 10);
;alert(globals);'>run: globals</div><br class='clear' /></div>
<p>
As well as silly things, like passing a <b>try/catch</b> statement directly
into a function call:
</p>
<div class='code'><pre><code>alert(
<span class="keyword">try</span>
nonexistent / <span class="literal">undefined</span>
<span class="keyword">catch</span> error
<span class="string">"And the error is ... <span class="subst">#{error}</span>"</span>
)
</code></pre><pre><code><span class="keyword">var</span> error;
alert((<span class="function"><span class="keyword">function</span><span class="params">()</span> {</span>
<span class="keyword">try</span> {
<span class="keyword">return</span> nonexistent / <span class="keyword">void</span> <span class="number">0</span>;
} <span class="keyword">catch</span> (_error) {
error = _error;
<span class="keyword">return</span> <span class="string">"And the error is ... "</span> + error;
}
})());
</code></pre><script>window.example19 = "alert(\n try\n nonexistent / undefined\n catch error\n \"And the error is ... #{error}\"\n)\n\n"</script><div class='minibutton load' onclick='javascript: loadConsole(example19);'>load</div><div class='minibutton ok' onclick='javascript: var error;
alert((function() {
try {
return nonexistent / void 0;
} catch (_error) {
error = _error;
return "And the error is ... " + error;
}
})());
;'>run</div><br class='clear' /></div>
<p>
There are a handful of statements in JavaScript that can't be meaningfully
converted into expressions, namely <tt>break</tt>, <tt>continue</tt>,
and <tt>return</tt>. If you make use of them within a block of code,
CoffeeScript won't try to perform the conversion.
</p>
<p>
<span id="operators" class="bookmark"></span>
<b class="header">Operators and Aliases</b>
Because the <tt>==</tt> operator frequently causes undesirable coercion,
is intransitive, and has a different meaning than in other languages,
CoffeeScript compiles <tt>==</tt> into <tt>===</tt>, and <tt>!=</tt> into
<tt>!==</tt>.
In addition, <tt>is</tt> compiles into <tt>===</tt>,
and <tt>isnt</tt> into <tt>!==</tt>.
</p>
<p>
You can use <tt>not</tt> as an alias for <tt>!</tt>.
</p>
<p>
For logic, <tt>and</tt> compiles to <tt>&amp;&amp;</tt>, and <tt>or</tt>
into <tt>||</tt>.
</p>
<p>
Instead of a newline or semicolon, <tt>then</tt> can be used to separate
conditions from expressions, in <b>while</b>,
<b>if</b>/<b>else</b>, and <b>switch</b>/<b>when</b> statements.
</p>
<p>
As in <a href="http://yaml.org/">YAML</a>, <tt>on</tt> and <tt>yes</tt>
are the same as boolean <tt>true</tt>, while <tt>off</tt> and <tt>no</tt> are boolean <tt>false</tt>.
</p>
<p>
<tt>unless</tt> can be used as the inverse of <tt>if</tt>.
</p>
<p>
As a shortcut for <tt>this.property</tt>, you can use <tt>@property</tt>.
</p>
<p>
You can use <tt>in</tt> to test for array presence, and <tt>of</tt> to
test for JavaScript object-key presence.
</p>
<p>
To simplify math expressions, <tt>**</tt> can be used for exponentiation, <tt>//</tt> performs integer division and <tt>%%</tt> provides true mathematical modulo.
</p>
<p>
All together now:
</p>
<table class="definitions">
<tr><th>CoffeeScript</th><th>JavaScript</th></tr>
<tr><td><tt>is</tt></td><td><tt>===</tt></td></tr>
<tr><td><tt>isnt</tt></td><td><tt>!==</tt></td></tr>
<tr><td><tt>not</tt></td><td><tt>!</tt></td></tr>
<tr><td><tt>and</tt></td><td><tt>&amp;&amp;</tt></td></tr>
<tr><td><tt>or</tt></td><td><tt>||</tt></td></tr>
<tr><td><tt>true</tt>, <tt>yes</tt>, <tt>on</tt></td><td><tt>true</tt></td></tr>
<tr><td><tt>false</tt>, <tt>no</tt>, <tt>off</tt></td><td><tt>false</tt></td></tr>
<tr><td><tt>@</tt>, <tt>this</tt></td><td><tt>this</tt></td></tr>
<tr><td><tt>of</tt></td><td><tt>in</tt></td></tr>
<tr><td><tt>in</tt></td><td><i><small>no JS equivalent</small></i></td></tr>
<tr><td><tt>a ** b</tt></td><td><tt>Math.pow(a, b)</tt></td></tr>
<tr><td><tt>a // b</tt></td><td><tt>Math.floor(a / b)</tt></td></tr>
<tr><td><tt>a %% b</tt></td><td><tt>(a % b + b) % b</tt></td></tr>
</table>
<div class='code'><pre><code>launch() <span class="keyword">if</span> ignition <span class="keyword">is</span> <span class="literal">on</span>
volume = <span class="number">10</span> <span class="keyword">if</span> band <span class="keyword">isnt</span> SpinalTap
letTheWildRumpusBegin() <span class="keyword">unless</span> answer <span class="keyword">is</span> <span class="literal">no</span>
<span class="keyword">if</span> car.speed &lt; limit <span class="keyword">then</span> accelerate()
winner = <span class="literal">yes</span> <span class="keyword">if</span> pick <span class="keyword">in</span> [<span class="number">47</span>, <span class="number">92</span>, <span class="number">13</span>]
<span class="built_in">print</span> inspect <span class="string">"My name is <span class="subst">#{<span class="property">@name</span>}</span>"</span>
</code></pre><pre><code><span class="keyword">var</span> volume, winner;
<span class="keyword">if</span> (ignition === <span class="literal">true</span>) {
launch();
}
<span class="keyword">if</span> (band !== SpinalTap) {
volume = <span class="number">10</span>;
}
<span class="keyword">if</span> (answer !== <span class="literal">false</span>) {
letTheWildRumpusBegin();
}
<span class="keyword">if</span> (car.speed &lt; limit) {
accelerate();
}
<span class="keyword">if</span> (pick === <span class="number">47</span> || pick === <span class="number">92</span> || pick === <span class="number">13</span>) {
winner = <span class="literal">true</span>;
}
print(inspect(<span class="string">"My name is "</span> + <span class="keyword">this</span>.name));
</code></pre><script>window.example20 = "launch() if ignition is on\n\nvolume = 10 if band isnt SpinalTap\n\nletTheWildRumpusBegin() unless answer is no\n\nif car.speed < limit then accelerate()\n\nwinner = yes if pick in [47, 92, 13]\n\nprint inspect \"My name is #{@name}\"\n"</script><div class='minibutton load' onclick='javascript: loadConsole(example20);'>load</div><br class='clear' /></div>
<p>
<b class="header">The Existential Operator</b>
It's a little difficult to check for the existence of a variable in
JavaScript. <tt>if (variable) ...</tt> comes close, but fails for zero,
the empty string, and false. CoffeeScript's existential operator <tt>?</tt> returns true unless
a variable is <b>null</b> or <b>undefined</b>, which makes it analogous
to Ruby's <tt>nil?</tt>
</p>
<p>
It can also be used for safer conditional assignment than <tt>||=</tt>
provides, for cases where you may be handling numbers or strings.
</p>
<div class='code'><pre><code>solipsism = <span class="literal">true</span> <span class="keyword">if</span> mind? <span class="keyword">and</span> <span class="keyword">not</span> world?
speed = <span class="number">0</span>
speed ?= <span class="number">15</span>
footprints = yeti ? <span class="string">"bear"</span>
</code></pre><pre><code><span class="keyword">var</span> footprints, solipsism, speed;
<span class="keyword">if</span> ((<span class="keyword">typeof</span> mind !== <span class="string">"undefined"</span> &amp;&amp; mind !== <span class="literal">null</span>) &amp;&amp; (<span class="keyword">typeof</span> world === <span class="string">"undefined"</span> || world === <span class="literal">null</span>)) {
solipsism = <span class="literal">true</span>;
}
speed = <span class="number">0</span>;
<span class="keyword">if</span> (speed == <span class="literal">null</span>) {
speed = <span class="number">15</span>;
}
footprints = <span class="keyword">typeof</span> yeti !== <span class="string">"undefined"</span> &amp;&amp; yeti !== <span class="literal">null</span> ? yeti : <span class="string">"bear"</span>;
</code></pre><script>window.example21 = "solipsism = true if mind? and not world?\n\nspeed = 0\nspeed ?= 15\n\nfootprints = yeti ? \"bear\"\n\n\n\n\n\n\n "</script><div class='minibutton load' onclick='javascript: loadConsole(example21);'>load</div><div class='minibutton ok' onclick='javascript: var footprints, solipsism, speed;
if ((typeof mind !== "undefined" && mind !== null) && (typeof world === "undefined" || world === null)) {
solipsism = true;
}
speed = 0;
if (speed == null) {
speed = 15;
}
footprints = typeof yeti !== "undefined" && yeti !== null ? yeti : "bear";
;alert(footprints);'>run: footprints</div><br class='clear' /></div>
<p>
The accessor variant of the existential operator <tt>?.</tt> can be used to soak
up null references in a chain of properties. Use it instead
of the dot accessor <tt>.</tt> in cases where the base value may be <b>null</b>
or <b>undefined</b>. If all of the properties exist then you'll get the expected
result, if the chain is broken, <b>undefined</b> is returned instead of
the <b>TypeError</b> that would be raised otherwise.
</p>
<div class='code'><pre><code>zip = lottery.drawWinner?().address?.zipcode
</code></pre><pre><code><span class="keyword">var</span> zip, _ref;
zip = <span class="keyword">typeof</span> lottery.drawWinner === <span class="string">"function"</span> ? (_ref = lottery.drawWinner().address) != <span class="literal">null</span> ? _ref.zipcode : <span class="keyword">void</span> <span class="number">0</span> : <span class="keyword">void</span> <span class="number">0</span>;
</code></pre><script>window.example22 = "zip = lottery.drawWinner?().address?.zipcode\n"</script><div class='minibutton load' onclick='javascript: loadConsole(example22);'>load</div><br class='clear' /></div>
<p>
Soaking up nulls is similar to Ruby's
<a href="http://andand.rubyforge.org/">andand gem</a>, and to the
<a href="http://groovy.codehaus.org/Operators#Operators-SafeNavigationOperator%28%3F.%29">safe navigation operator</a>
in Groovy.
</p>
<p>
<span id="classes" class="bookmark"></span>
<b class="header">Classes, Inheritance, and Super</b>
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:
<a href="http://code.google.com/p/base2/">Base2</a>,
<a href="http://prototypejs.org/">Prototype.js</a>,
<a href="http://jsclass.jcoglan.com/">JS.Class</a>, 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 <b>super</b> (the prototype object's
implementation of the current function), and it's awkward to correctly
set the prototype chain.
</p>
<p>
Instead of repetitively attaching functions to a prototype, CoffeeScript
provides a basic <tt>class</tt> structure that allows you to name your class,
set the superclass, assign prototypal properties, and define the constructor,
in a single assignable expression.
</p>
<p>
Constructor functions are named, to better support helpful stack traces.
In the first class in the example below, <tt>this.constructor.name is "Animal"</tt>.
</p>
<div class='code'><pre><code><span class="class"><span class="keyword">class</span> <span class="title">Animal</span></span>
<span class="attribute">constructor</span>: <span class="function"><span class="params">(<span class="property">@name</span>)</span> -&gt;</span>
<span class="attribute">move</span>: <span class="function"><span class="params">(meters)</span> -&gt;</span>
alert <span class="property">@name</span> + <span class="string">" moved <span class="subst">#{meters}</span>m."</span>
<span class="class"><span class="keyword">class</span> <span class="title">Snake</span> <span class="keyword">extends</span> <span class="title">Animal</span></span>
<span class="attribute">move</span>:<span class="function"> -&gt;</span>
alert <span class="string">"Slithering..."</span>
<span class="keyword">super</span> <span class="number">5</span>
<span class="class"><span class="keyword">class</span> <span class="title">Horse</span> <span class="keyword">extends</span> <span class="title">Animal</span></span>
<span class="attribute">move</span>:<span class="function"> -&gt;</span>
alert <span class="string">"Galloping..."</span>
<span class="keyword">super</span> <span class="number">45</span>
sam = <span class="keyword">new</span> Snake <span class="string">"Sammy the Python"</span>
tom = <span class="keyword">new</span> Horse <span class="string">"Tommy the Palomino"</span>
sam.move()
tom.move()
</code></pre><pre><code><span class="keyword">var</span> Animal, Horse, Snake, sam, tom,
__hasProp = {}.hasOwnProperty,
__extends = <span class="function"><span class="keyword">function</span><span class="params">(child, parent)</span> {</span> <span class="keyword">for</span> (<span class="keyword">var</span> key <span class="keyword">in</span> parent) { <span class="keyword">if</span> (__hasProp.call(parent, key)) child[key] = parent[key]; } <span class="function"><span class="keyword">function</span> <span class="title">ctor</span><span class="params">()</span> {</span> <span class="keyword">this</span>.constructor = child; } ctor.prototype = parent.prototype; child.prototype = <span class="keyword">new</span> ctor(); child.__super__ = parent.prototype; <span class="keyword">return</span> child; };
Animal = (<span class="function"><span class="keyword">function</span><span class="params">()</span> {</span>
<span class="function"><span class="keyword">function</span> <span class="title">Animal</span><span class="params">(name)</span> {</span>
<span class="keyword">this</span>.name = name;
}
Animal.prototype.move = <span class="function"><span class="keyword">function</span><span class="params">(meters)</span> {</span>
<span class="keyword">return</span> alert(<span class="keyword">this</span>.name + (<span class="string">" moved "</span> + meters + <span class="string">"m."</span>));
};
<span class="keyword">return</span> Animal;
})();
Snake = (<span class="function"><span class="keyword">function</span><span class="params">(_super)</span> {</span>
__extends(Snake, _super);
<span class="function"><span class="keyword">function</span> <span class="title">Snake</span><span class="params">()</span> {</span>
<span class="keyword">return</span> Snake.__super__.constructor.apply(<span class="keyword">this</span>, <span class="built_in">arguments</span>);
}
Snake.prototype.move = <span class="function"><span class="keyword">function</span><span class="params">()</span> {</span>
alert(<span class="string">"Slithering..."</span>);
<span class="keyword">return</span> Snake.__super__.move.call(<span class="keyword">this</span>, <span class="number">5</span>);
};
<span class="keyword">return</span> Snake;
})(Animal);
Horse = (<span class="function"><span class="keyword">function</span><span class="params">(_super)</span> {</span>
__extends(Horse, _super);
<span class="function"><span class="keyword">function</span> <span class="title">Horse</span><span class="params">()</span> {</span>
<span class="keyword">return</span> Horse.__super__.constructor.apply(<span class="keyword">this</span>, <span class="built_in">arguments</span>);
}
Horse.prototype.move = <span class="function"><span class="keyword">function</span><span class="params">()</span> {</span>
alert(<span class="string">"Galloping..."</span>);
<span class="keyword">return</span> Horse.__super__.move.call(<span class="keyword">this</span>, <span class="number">45</span>);
};
<span class="keyword">return</span> Horse;
})(Animal);
sam = <span class="keyword">new</span> Snake(<span class="string">"Sammy the Python"</span>);
tom = <span class="keyword">new</span> Horse(<span class="string">"Tommy the Palomino"</span>);
sam.move();
tom.move();
</code></pre><script>window.example23 = "class Animal\n constructor: (@name) ->\n\n move: (meters) ->\n alert @name + \" moved #{meters}m.\"\n\nclass Snake extends Animal\n move: ->\n alert \"Slithering...\"\n super 5\n\nclass Horse extends Animal\n move: ->\n alert \"Galloping...\"\n super 45\n\nsam = new Snake \"Sammy the Python\"\ntom = new Horse \"Tommy the Palomino\"\n\nsam.move()\ntom.move()\n\n\n\n\n"</script><div class='minibutton load' onclick='javascript: loadConsole(example23);'>load</div><div class='minibutton ok' onclick='javascript: var Animal, Horse, Snake, sam, tom,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Animal = (function() {
function Animal(name) {
this.name = name;
}
Animal.prototype.move = function(meters) {
return alert(this.name + (" moved " + meters + "m."));
};
return Animal;
})();
Snake = (function(_super) {
__extends(Snake, _super);
function Snake() {
return Snake.__super__.constructor.apply(this, arguments);
}
Snake.prototype.move = function() {
alert("Slithering...");
return Snake.__super__.move.call(this, 5);
};
return Snake;
})(Animal);
Horse = (function(_super) {
__extends(Horse, _super);
function Horse() {
return Horse.__super__.constructor.apply(this, arguments);
}
Horse.prototype.move = function() {
alert("Galloping...");
return Horse.__super__.move.call(this, 45);
};
return Horse;
})(Animal);
sam = new Snake("Sammy the Python");
tom = new Horse("Tommy the Palomino");
sam.move();
tom.move();
;'>run</div><br class='clear' /></div>
<p>
If structuring your prototypes classically isn't your cup of tea, CoffeeScript
provides a couple of lower-level conveniences. The <tt>extends</tt> operator
helps with proper prototype setup, and can be used to create an inheritance
chain between any pair of constructor functions; <tt>::</tt> gives you
quick access to an object's prototype; and <tt>super()</tt>
is converted into a call against the immediate ancestor's method of the same name.
</p>
<div class='code'><pre><code><span class="attribute">String</span>::<span class="function"><span class="title">dasherize</span> = -&gt;</span>
<span class="keyword">this</span>.replace <span class="regexp">/_/g</span>, <span class="string">"-"</span>
</code></pre><pre><code><span class="built_in">String</span>.prototype.dasherize = <span class="function"><span class="keyword">function</span><span class="params">()</span> {</span>
<span class="keyword">return</span> <span class="keyword">this</span>.replace(<span class="regexp">/_/g</span>, <span class="string">"-"</span>);
};
</code></pre><script>window.example24 = "String::dasherize = ->\n this.replace /_/g, \"-\"\n\n"</script><div class='minibutton load' onclick='javascript: loadConsole(example24);'>load</div><div class='minibutton ok' onclick='javascript: String.prototype.dasherize = function() {
return this.replace(/_/g, "-");
};
;alert("one_two".dasherize());'>run: "one_two".dasherize()</div><br class='clear' /></div>
<p>
Finally, class definitions are blocks of executable code, which make for interesting
metaprogramming possibilities. Because in the context of a class definition,
<tt>this</tt> is the class object itself (the constructor function), you
can assign static properties by using <br /><tt>@property: value</tt>, and call
functions defined in parent classes: <tt>@attr 'title', type: 'text'</tt>
</p>
<p>
<span id="destructuring" class="bookmark"></span>
<b class="header">Destructuring Assignment</b>
To make extracting values from complex arrays and objects more convenient,
CoffeeScript implements ECMAScript Harmony's proposed
<a href="http://wiki.ecmascript.org/doku.php?id=harmony:destructuring">destructuring assignment</a>
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:
</p>
<div class='code'><pre><code>theBait = <span class="number">1000</span>
theSwitch = <span class="number">0</span>
[theBait, theSwitch] = [theSwitch, theBait]
</code></pre><pre><code><span class="keyword">var</span> theBait, theSwitch, _ref;
theBait = <span class="number">1000</span>;
theSwitch = <span class="number">0</span>;
_ref = [theSwitch, theBait], theBait = _ref[<span class="number">0</span>], theSwitch = _ref[<span class="number">1</span>];
</code></pre><script>window.example25 = "theBait = 1000\ntheSwitch = 0\n\n[theBait, theSwitch] = [theSwitch, theBait]\n\n\n\n\n "</script><div class='minibutton load' onclick='javascript: loadConsole(example25);'>load</div><div class='minibutton ok' onclick='javascript: var theBait, theSwitch, _ref;
theBait = 1000;
theSwitch = 0;
_ref = [theSwitch, theBait], theBait = _ref[0], theSwitch = _ref[1];
;alert(theBait);'>run: theBait</div><br class='clear' /></div>
<p>
But it's also helpful for dealing with functions that return multiple
values.
</p>
<div class='code'><pre><code><span class="function"><span class="title">weatherReport</span> = <span class="params">(location)</span> -&gt;</span>
<span class="comment"># Make an Ajax request to fetch the weather...</span>
[location, <span class="number">72</span>, <span class="string">"Mostly Sunny"</span>]
[city, temp, forecast] = weatherReport <span class="string">"Berkeley, CA"</span>
</code></pre><pre><code><span class="keyword">var</span> city, forecast, temp, weatherReport, _ref;
weatherReport = <span class="function"><span class="keyword">function</span><span class="params">(location)</span> {</span>
<span class="keyword">return</span> [location, <span class="number">72</span>, <span class="string">"Mostly Sunny"</span>];
};
_ref = weatherReport(<span class="string">"Berkeley, CA"</span>), city = _ref[<span class="number">0</span>], temp = _ref[<span class="number">1</span>], forecast = _ref[<span class="number">2</span>];
</code></pre><script>window.example26 = "weatherReport = (location) ->\n # Make an Ajax request to fetch the weather...\n [location, 72, \"Mostly Sunny\"]\n\n[city, temp, forecast] = weatherReport \"Berkeley, CA\"\n\n\n\n\n"</script><div class='minibutton load' onclick='javascript: loadConsole(example26);'>load</div><div class='minibutton ok' onclick='javascript: var city, forecast, temp, weatherReport, _ref;
weatherReport = function(location) {
return [location, 72, "Mostly Sunny"];
};
_ref = weatherReport("Berkeley, CA"), city = _ref[0], temp = _ref[1], forecast = _ref[2];
;alert(forecast);'>run: forecast</div><br class='clear' /></div>
<p>
Destructuring assignment can be used with any depth of array and object nesting,
to help pull out deeply nested properties.
</p>
<div class='code'><pre><code>futurists =
<span class="attribute">sculptor</span>: <span class="string">"Umberto Boccioni"</span>
<span class="attribute">painter</span>: <span class="string">"Vladimir Burliuk"</span>
<span class="attribute">poet</span>:
<span class="attribute">name</span>: <span class="string">"F.T. Marinetti"</span>
<span class="attribute">address</span>: [
<span class="string">"Via Roma 42R"</span>
<span class="string">"Bellagio, Italy 22021"</span>
]
{<span class="attribute">poet</span>: {name, <span class="attribute">address</span>: [street, city]}} = futurists
</code></pre><pre><code><span class="keyword">var</span> city, futurists, name, street, _ref, _ref1;
futurists = {
sculptor: <span class="string">"Umberto Boccioni"</span>,
painter: <span class="string">"Vladimir Burliuk"</span>,
poet: {
name: <span class="string">"F.T. Marinetti"</span>,
address: [<span class="string">"Via Roma 42R"</span>, <span class="string">"Bellagio, Italy 22021"</span>]
}
};
_ref = futurists.poet, name = _ref.name, (_ref1 = _ref.address, street = _ref1[<span class="number">0</span>], city = _ref1[<span class="number">1</span>]);
</code></pre><script>window.example27 = "futurists =\n sculptor: \"Umberto Boccioni\"\n painter: \"Vladimir Burliuk\"\n poet:\n name: \"F.T. Marinetti\"\n address: [\n \"Via Roma 42R\"\n \"Bellagio, Italy 22021\"\n ]\n\n{poet: {name, address: [street, city]}} = futurists\n\n\n\n"</script><div class='minibutton load' onclick='javascript: loadConsole(example27);'>load</div><div class='minibutton ok' onclick='javascript: var city, futurists, name, street, _ref, _ref1;
futurists = {
sculptor: "Umberto Boccioni",
painter: "Vladimir Burliuk",
poet: {
name: "F.T. Marinetti",
address: ["Via Roma 42R", "Bellagio, Italy 22021"]
}
};
_ref = futurists.poet, name = _ref.name, (_ref1 = _ref.address, street = _ref1[0], city = _ref1[1]);
;alert(name + "-" + street);'>run: name + "-" + street</div><br class='clear' /></div>
<p>
Destructuring assignment can even be combined with splats.
</p>
<div class='code'><pre><code>tag = <span class="string">"&lt;impossible&gt;"</span>
[open, contents..., close] = tag.split(<span class="string">""</span>)
</code></pre><pre><code><span class="keyword">var</span> close, contents, open, tag, _i, _ref,
__slice = [].slice;
tag = <span class="string">"&lt;impossible&gt;"</span>;
_ref = tag.split(<span class="string">""</span>), open = _ref[<span class="number">0</span>], contents = <span class="number">3</span> &lt;= _ref.length ? __slice.call(_ref, <span class="number">1</span>, _i = _ref.length - <span class="number">1</span>) : (_i = <span class="number">1</span>, []), close = _ref[_i++];
</code></pre><script>window.example28 = "tag = \"<impossible>\"\n\n[open, contents..., close] = tag.split(\"\")\n\n\n\n\n\n\n"</script><div class='minibutton load' onclick='javascript: loadConsole(example28);'>load</div><div class='minibutton ok' onclick='javascript: var close, contents, open, tag, _i, _ref,
__slice = [].slice;
tag = "<impossible>";
_ref = tag.split(""), open = _ref[0], contents = 3 <= _ref.length ? __slice.call(_ref, 1, _i = _ref.length - 1) : (_i = 1, []), close = _ref[_i++];
;alert(contents.join(""));'>run: contents.join("")</div><br class='clear' /></div>
<p>
Expansion can be used to retrieve elements from the end of an array without having to assign the rest of its values. It works in function parameter lists as well.
</p>
<div class='code'><pre><code>text = <span class="string">"Every literary critic believes he will
outwit history and have the last word"</span>
[first, ..., last] = text.split <span class="string">" "</span>
</code></pre><pre><code><span class="keyword">var</span> first, last, text, _ref;
text = <span class="string">"Every literary critic believes he will outwit history and have the last word"</span>;
_ref = text.split(<span class="string">" "</span>), first = _ref[<span class="number">0</span>], last = _ref[_ref.length - <span class="number">1</span>];
</code></pre><script>window.example29 = "text = \"Every literary critic believes he will\n outwit history and have the last word\"\n\n[first, ..., last] = text.split \" \"\n\n\n\n"</script><div class='minibutton load' onclick='javascript: loadConsole(example29);'>load</div><div class='minibutton ok' onclick='javascript: var first, last, text, _ref;
text = "Every literary critic believes he will outwit history and have the last word";
_ref = text.split(" "), first = _ref[0], last = _ref[_ref.length - 1];
;alert(first + " " + last);'>run: first + " " + last</div><br class='clear' /></div>
<p>
Destructuring assignment is also useful when combined with class constructors
to assign properties to your instance from an options object passed to the constructor.
</p>
<div class='code'><pre><code><span class="class"><span class="keyword">class</span> <span class="title">Person</span></span>
<span class="attribute">constructor</span>: <span class="function"><span class="params">(options)</span> -&gt;</span>
{<span class="property">@name</span>, <span class="property">@age</span>, <span class="property">@height</span>} = options
tim = <span class="keyword">new</span> Person <span class="attribute">age</span>: <span class="number">4</span>
</code></pre><pre><code><span class="keyword">var</span> Person, tim;
Person = (<span class="function"><span class="keyword">function</span><span class="params">()</span> {</span>
<span class="function"><span class="keyword">function</span> <span class="title">Person</span><span class="params">(options)</span> {</span>
<span class="keyword">this</span>.name = options.name, <span class="keyword">this</span>.age = options.age, <span class="keyword">this</span>.height = options.height;
}
<span class="keyword">return</span> Person;
})();
tim = <span class="keyword">new</span> Person({
age: <span class="number">4</span>
});
</code></pre><script>window.example30 = "class Person\n constructor: (options) -> \n {@name, @age, @height} = options\n\ntim = new Person age: 4\n\n"</script><div class='minibutton load' onclick='javascript: loadConsole(example30);'>load</div><div class='minibutton ok' onclick='javascript: var Person, tim;
Person = (function() {
function Person(options) {
this.name = options.name, this.age = options.age, this.height = options.height;
}
return Person;
})();
tim = new Person({
age: 4
});
;alert(tim.age);'>run: tim.age</div><br class='clear' /></div>
<p>
<span id="fat-arrow" class="bookmark"></span>
<b class="header">Function binding</b>
In JavaScript, the <tt>this</tt> keyword is dynamically scoped to mean the
object that the current function is attached to. If you pass a function as
a callback or attach it to a different object, the original value of <tt>this</tt>
will be lost. If you're not familiar with this behavior,
<a href="http://www.digital-web.com/articles/scope_in_javascript/">this Digital Web article</a>
gives a good overview of the quirks.
</p>
<p>
The fat arrow <tt>=&gt;</tt> can be used to both define a function, and to bind
it to the current value of <tt>this</tt>, right on the spot. This is helpful
when using callback-based libraries like Prototype or jQuery, for creating
iterator functions to pass to <tt>each</tt>, or event-handler functions
to use with <tt>bind</tt>. Functions created with the fat arrow are able to access
properties of the <tt>this</tt> where they're defined.
</p>
<div class='code'><pre><code><span class="function"><span class="title">Account</span> = <span class="params">(customer, cart)</span> -&gt;</span>
<span class="property">@customer</span> = customer
<span class="property">@cart</span> = cart
$<span class="function"><span class="params">(<span class="string">'.shopping_cart'</span>)</span>.<span class="title">bind</span> '<span class="title">click</span>', <span class="params">(event)</span> =&gt;</span>
<span class="property">@customer</span>.purchase <span class="property">@cart</span></code></pre><pre><code><span class="keyword">var</span> Account;
Account = <span class="function"><span class="keyword">function</span><span class="params">(customer, cart)</span> {</span>
<span class="keyword">this</span>.customer = customer;
<span class="keyword">this</span>.cart = cart;
<span class="keyword">return</span> $(<span class="string">'.shopping_cart'</span>).bind(<span class="string">'click'</span>, (<span class="function"><span class="keyword">function</span><span class="params">(_this)</span> {</span>
<span class="keyword">return</span> <span class="function"><span class="keyword">function</span><span class="params">(event)</span> {</span>
<span class="keyword">return</span> _this.customer.purchase(_this.cart);
};
})(<span class="keyword">this</span>));
};
</code></pre><script>window.example31 = "Account = (customer, cart) ->\n @customer = customer\n @cart = cart\n\n $('.shopping_cart').bind 'click', (event) =>\n @customer.purchase @cart"</script><div class='minibutton load' onclick='javascript: loadConsole(example31);'>load</div><br class='clear' /></div>
<p>
If we had used <tt>-&gt;</tt> in the callback above, <tt>@customer</tt> would
have referred to the undefined "customer" property of the DOM element,
and trying to call <tt>purchase()</tt> on it would have raised an exception.
</p>
<p>
When used in a class definition, methods declared with the fat arrow will
be automatically bound to each instance of the class when the instance is
constructed.
</p>
<p>
<span id="embedded" class="bookmark"></span>
<b class="header">Embedded JavaScript</b>
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.
</p>
<div class='code'><pre><code>hi = `<span class="javascript"><span class="function"><span class="keyword">function</span><span class="params">()</span> {</span>
<span class="keyword">return</span> [document.title, <span class="string">"Hello JavaScript"</span>].join(<span class="string">": "</span>);
}</span>`
</code></pre><pre><code><span class="keyword">var</span> hi;
hi = <span class="function"><span class="keyword">function</span><span class="params">()</span> {</span>
<span class="keyword">return</span> [document.title, <span class="string">"Hello JavaScript"</span>].join(<span class="string">": "</span>);
};
</code></pre><script>window.example32 = "hi = `function() {\n return [document.title, \"Hello JavaScript\"].join(\": \");\n}`\n\n\n\n"</script><div class='minibutton load' onclick='javascript: loadConsole(example32);'>load</div><div class='minibutton ok' onclick='javascript: var hi;
hi = function() {
return [document.title, "Hello JavaScript"].join(": ");
};
;alert(hi());'>run: hi()</div><br class='clear' /></div>
<p>
<span id="switch" class="bookmark"></span>
<b class="header">Switch/When/Else</b>
<b>Switch</b> statements in JavaScript are a bit awkward. You need to
remember to <b>break</b> at the end of every <b>case</b> statement to
avoid accidentally falling through to the default case.
CoffeeScript prevents accidental fall-through, and can convert the <tt>switch</tt>
into a returnable, assignable expression. The format is: <tt>switch</tt> condition,
<tt>when</tt> clauses, <tt>else</tt> the default case.
</p>
<p>
As in Ruby, <b>switch</b> statements in CoffeeScript can take multiple
values for each <b>when</b> clause. If any of the values match, the clause
runs.
</p>
<div class='code'><pre><code><span class="keyword">switch</span> day
<span class="keyword">when</span> <span class="string">"Mon"</span> <span class="keyword">then</span> go work
<span class="keyword">when</span> <span class="string">"Tue"</span> <span class="keyword">then</span> go relax
<span class="keyword">when</span> <span class="string">"Thu"</span> <span class="keyword">then</span> go iceFishing
<span class="keyword">when</span> <span class="string">"Fri"</span>, <span class="string">"Sat"</span>
<span class="keyword">if</span> day <span class="keyword">is</span> bingoDay
go bingo
go dancing
<span class="keyword">when</span> <span class="string">"Sun"</span> <span class="keyword">then</span> go church
<span class="keyword">else</span> go work</code></pre><pre><code><span class="keyword">switch</span> (day) {
<span class="keyword">case</span> <span class="string">"Mon"</span>:
go(work);
<span class="keyword">break</span>;
<span class="keyword">case</span> <span class="string">"Tue"</span>:
go(relax);
<span class="keyword">break</span>;
<span class="keyword">case</span> <span class="string">"Thu"</span>:
go(iceFishing);
<span class="keyword">break</span>;
<span class="keyword">case</span> <span class="string">"Fri"</span>:
<span class="keyword">case</span> <span class="string">"Sat"</span>:
<span class="keyword">if</span> (day === bingoDay) {
go(bingo);
go(dancing);
}
<span class="keyword">break</span>;
<span class="keyword">case</span> <span class="string">"Sun"</span>:
go(church);
<span class="keyword">break</span>;
<span class="keyword">default</span>:
go(work);
}
</code></pre><script>window.example33 = "switch day\n when \"Mon\" then go work\n when \"Tue\" then go relax\n when \"Thu\" then go iceFishing\n when \"Fri\", \"Sat\"\n if day is bingoDay\n go bingo\n go dancing\n when \"Sun\" then go church\n else go work"</script><div class='minibutton load' onclick='javascript: loadConsole(example33);'>load</div><br class='clear' /></div>
<p>
Switch statements can also be used without a control expression, turning them in to a cleaner alternative to if/else chains.
</p>
<div class='code'><pre><code>score = <span class="number">76</span>
grade = <span class="keyword">switch</span>
<span class="keyword">when</span> score &lt; <span class="number">60</span> <span class="keyword">then</span> <span class="string">'F'</span>
<span class="keyword">when</span> score &lt; <span class="number">70</span> <span class="keyword">then</span> <span class="string">'D'</span>
<span class="keyword">when</span> score &lt; <span class="number">80</span> <span class="keyword">then</span> <span class="string">'C'</span>
<span class="keyword">when</span> score &lt; <span class="number">90</span> <span class="keyword">then</span> <span class="string">'B'</span>
<span class="keyword">else</span> <span class="string">'A'</span>
<span class="comment"># grade == 'C'</span>
</code></pre><pre><code><span class="keyword">var</span> grade, score;
score = <span class="number">76</span>;
grade = (<span class="function"><span class="keyword">function</span><span class="params">()</span> {</span>
<span class="keyword">switch</span> (<span class="literal">false</span>) {
<span class="keyword">case</span> !(score &lt; <span class="number">60</span>):
<span class="keyword">return</span> <span class="string">'F'</span>;
<span class="keyword">case</span> !(score &lt; <span class="number">70</span>):
<span class="keyword">return</span> <span class="string">'D'</span>;
<span class="keyword">case</span> !(score &lt; <span class="number">80</span>):
<span class="keyword">return</span> <span class="string">'C'</span>;
<span class="keyword">case</span> !(score &lt; <span class="number">90</span>):
<span class="keyword">return</span> <span class="string">'B'</span>;
<span class="keyword">default</span>:
<span class="keyword">return</span> <span class="string">'A'</span>;
}
})();
</code></pre><script>window.example34 = "score = 76\ngrade = switch\n when score < 60 then 'F'\n when score < 70 then 'D'\n when score < 80 then 'C'\n when score < 90 then 'B'\n else 'A'\n# grade == 'C'\n"</script><div class='minibutton load' onclick='javascript: loadConsole(example34);'>load</div><br class='clear' /></div>
<p>
<span id="try" class="bookmark"></span>
<b class="header">Try/Catch/Finally</b>
Try/catch statements are just about the same as JavaScript (although
they work as expressions).
</p>
<div class='code'><pre><code><span class="keyword">try</span>
allHellBreaksLoose()
catsAndDogsLivingTogether()
<span class="keyword">catch</span> error
<span class="built_in">print</span> error
<span class="keyword">finally</span>
cleanUp()
</code></pre><pre><code><span class="keyword">var</span> error;
<span class="keyword">try</span> {
allHellBreaksLoose();
catsAndDogsLivingTogether();
} <span class="keyword">catch</span> (_error) {
error = _error;
print(error);
} <span class="keyword">finally</span> {
cleanUp();
}
</code></pre><script>window.example35 = "try\n allHellBreaksLoose()\n catsAndDogsLivingTogether()\ncatch error\n print error\nfinally\n cleanUp()\n\n"</script><div class='minibutton load' onclick='javascript: loadConsole(example35);'>load</div><br class='clear' /></div>
<p>
<span id="comparisons" class="bookmark"></span>
<b class="header">Chained Comparisons</b>
CoffeeScript borrows
<a href="http://docs.python.org/reference/expressions.html#notin">chained comparisons</a>
from Python &mdash; making it easy to test if a value falls within a
certain range.
</p>
<div class='code'><pre><code>cholesterol = <span class="number">127</span>
healthy = <span class="number">200</span> &gt; cholesterol &gt; <span class="number">60</span>
</code></pre><pre><code><span class="keyword">var</span> cholesterol, healthy;
cholesterol = <span class="number">127</span>;
healthy = (<span class="number">200</span> &gt; cholesterol &amp;&amp; cholesterol &gt; <span class="number">60</span>);
</code></pre><script>window.example36 = "cholesterol = 127\n\nhealthy = 200 > cholesterol > 60\n\n\n"</script><div class='minibutton load' onclick='javascript: loadConsole(example36);'>load</div><div class='minibutton ok' onclick='javascript: var cholesterol, healthy;
cholesterol = 127;
healthy = (200 > cholesterol && cholesterol > 60);
;alert(healthy);'>run: healthy</div><br class='clear' /></div>
<p>
<span id="strings" class="bookmark"></span>
<b class="header">String Interpolation, Block Strings, and Block Comments</b>
Ruby-style string interpolation is included in CoffeeScript. Double-quoted
strings allow for interpolated values, using <tt>#{ ... }</tt>,
and single-quoted strings are literal.
</p>
<div class='code'><pre><code>author = <span class="string">"Wittgenstein"</span>
quote = <span class="string">"A picture is a fact. -- <span class="subst">#{ author }</span>"</span>
sentence = <span class="string">"<span class="subst">#{ <span class="number">22</span> / <span class="number">7</span> }</span> is a decent approximation of π"</span>
</code></pre><pre><code><span class="keyword">var</span> author, quote, sentence;
author = <span class="string">"Wittgenstein"</span>;
quote = <span class="string">"A picture is a fact. -- "</span> + author;
sentence = <span class="string">""</span> + (<span class="number">22</span> / <span class="number">7</span>) + <span class="string">" is a decent approximation of π"</span>;
</code></pre><script>window.example37 = "author = \"Wittgenstein\"\nquote = \"A picture is a fact. -- #{ author }\"\n\nsentence = \"#{ 22 / 7 } is a decent approximation of π\"\n\n\n\n\n\n"</script><div class='minibutton load' onclick='javascript: loadConsole(example37);'>load</div><div class='minibutton ok' onclick='javascript: var author, quote, sentence;
author = "Wittgenstein";
quote = "A picture is a fact. -- " + author;
sentence = "" + (22 / 7) + " is a decent approximation of π";
;alert(sentence);'>run: sentence</div><br class='clear' /></div>
<p>
Multiline strings are allowed in CoffeeScript. Lines are joined by a single space unless they end with a backslash. Indentation is ignored.
</p>
<div class='code'><pre><code>mobyDick = <span class="string">"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..."</span>
</code></pre><pre><code><span class="keyword">var</span> mobyDick;
mobyDick = <span class="string">"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..."</span>;
</code></pre><script>window.example38 = "mobyDick = \"Call me Ishmael. Some years ago --\n never mind how long precisely -- having little\n or no money in my purse, and nothing particular\n to interest me on shore, I thought I would sail\n about a little and see the watery part of the\n world...\"\n"</script><div class='minibutton load' onclick='javascript: loadConsole(example38);'>load</div><div class='minibutton ok' onclick='javascript: var mobyDick;
mobyDick = "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...";
;alert(mobyDick);'>run: mobyDick</div><br class='clear' /></div>
<p>
Block strings 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 block is maintained throughout, so
you can keep it all aligned with the body of your code.
</p>
<div class='code'><pre><code>html = <span class="string">"""
&lt;strong&gt;
cup of coffeescript
&lt;/strong&gt;
"""</span>
</code></pre><pre><code><span class="keyword">var</span> html;
html = <span class="string">"&lt;strong&gt;\n cup of coffeescript\n&lt;/strong&gt;"</span>;
</code></pre><script>window.example39 = "html = \"\"\"\n <strong>\n cup of coffeescript\n </strong>\n \"\"\"\n \n"</script><div class='minibutton load' onclick='javascript: loadConsole(example39);'>load</div><div class='minibutton ok' onclick='javascript: var html;
html = "<strong>\n cup of coffeescript\n</strong>";
;alert(html);'>run: html</div><br class='clear' /></div>
<p>
Double-quoted block strings, like other double-quoted strings, allow interpolation.
</p>
<p>
Sometimes you'd like to pass a block comment through to the generated
JavaScript. For example, when you need to embed a licensing header at
the top of a file. Block comments, which mirror the syntax for block strings,
are preserved in the generated code.
</p>
<div class='code'><pre><code><span class="comment">###
SkinnyMochaHalfCaffScript Compiler v1.0
Released under the MIT License
###</span>
</code></pre><pre><code>
<span class="comment">/*
SkinnyMochaHalfCaffScript Compiler v1.0
Released under the MIT License
*/</span>
</code></pre><script>window.example40 = "###\nSkinnyMochaHalfCaffScript Compiler v1.0\nReleased under the MIT License\n###\n\n\n"</script><div class='minibutton load' onclick='javascript: loadConsole(example40);'>load</div><br class='clear' /></div>
<p>
<span id="regexes" class="bookmark"></span>
<b class="header">Block Regular Expressions</b>
Similar to block strings and comments, CoffeeScript supports block regexes &mdash;
extended regular expressions that ignore internal whitespace and can contain
comments and interpolation. Modeled after Perl's <tt>/x</tt> modifier, CoffeeScript's
block regexes are delimited by <tt>///</tt> and go a long way towards making complex
regular expressions readable. To quote from the CoffeeScript source:
</p>
<div class='code'><pre><code>OPERATOR = <span class="regexp">/// ^ (
?: [-=]&gt; <span class="comment"># function</span>
| [-+*/%&lt;&gt;&amp;|^!?=]= <span class="comment"># compound assign / compare</span>
| &gt;&gt;&gt;=? <span class="comment"># zero-fill right shift</span>
| ([-+:])\1 <span class="comment"># doubles</span>
| ([&amp;|&lt;&gt;])\2=? <span class="comment"># logic / shift</span>
| \?\. <span class="comment"># soak access</span>
| \.{2,3} <span class="comment"># range or splat</span>
) ///</span>
</code></pre><pre><code><span class="keyword">var</span> OPERATOR;
OPERATOR = <span class="regexp">/^(?:[-=]&gt;|[-+*\/%&lt;&gt;&amp;|^!?=]=|&gt;&gt;&gt;=?|([-+:])\1|([&amp;|&lt;&gt;])\2=?|\?\.|\.{2,3})/</span>;
</code></pre><script>window.example41 = "OPERATOR = /// ^ (\n ?: [-=]> # function\n | [-+*/%<>&|^!?=]= # compound assign / compare\n | >>>=? # zero-fill right shift\n | ([-+:])\\1 # doubles\n | ([&|<>])\\2=? # logic / shift\n | \\?\\. # soak access\n | \\.{2,3} # range or splat\n) ///\n\n\n"</script><div class='minibutton load' onclick='javascript: loadConsole(example41);'>load</div><br class='clear' /></div>
<h2>
<span id="cake" class="bookmark"></span>
Cake, and Cakefiles
</h2>
<p>
CoffeeScript includes a (very) simple build system similar to
<a href="http://www.gnu.org/software/make/">Make</a> and
<a href="http://rake.rubyforge.org/">Rake</a>. Naturally,
it's called Cake, and is used for the tasks that build and test the CoffeeScript
language itself. Tasks are defined in a file named <tt>Cakefile</tt>, and
can be invoked by running <tt>cake [task]</tt> from within the directory.
To print a list of all the tasks and options, just type <tt>cake</tt>.
</p>
<p>
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. If your task takes a command-line
option, you can define the option with short and long flags, and it will
be made available in the <tt>options</tt> object. Here's a task that uses
the Node.js API to rebuild CoffeeScript's parser:
</p>
<div class='code'><pre><code>fs = <span class="built_in">require</span> <span class="string">'fs'</span>
option <span class="string">'-o'</span>, <span class="string">'--output [DIR]'</span>, <span class="string">'directory for compiled code'</span>
task <span class="string">'build:parser'</span>, <span class="string">'rebuild the Jison parser'</span>, <span class="function"><span class="params">(options)</span> -&gt;</span>
<span class="built_in">require</span> <span class="string">'jison'</span>
code = <span class="built_in">require</span>(<span class="string">'./lib/grammar'</span>).parser.generate()
dir = options.output <span class="keyword">or</span> <span class="string">'lib'</span>
fs.writeFile <span class="string">"<span class="subst">#{dir}</span>/parser.js"</span>, code</code></pre><pre><code><span class="keyword">var</span> fs;
fs = <span class="built_in">require</span>(<span class="string">'fs'</span>);
option(<span class="string">'-o'</span>, <span class="string">'--output [DIR]'</span>, <span class="string">'directory for compiled code'</span>);
task(<span class="string">'build:parser'</span>, <span class="string">'rebuild the Jison parser'</span>, <span class="function"><span class="keyword">function</span><span class="params">(options)</span> {</span>
<span class="keyword">var</span> code, dir;
<span class="built_in">require</span>(<span class="string">'jison'</span>);
code = <span class="built_in">require</span>(<span class="string">'./lib/grammar'</span>).parser.generate();
dir = options.output || <span class="string">'lib'</span>;
<span class="keyword">return</span> fs.writeFile(<span class="string">""</span> + dir + <span class="string">"/parser.js"</span>, code);
});
</code></pre><script>window.example42 = "fs = require 'fs'\n\noption '-o', '--output [DIR]', 'directory for compiled code'\n\ntask 'build:parser', 'rebuild the Jison parser', (options) ->\n require 'jison'\n code = require('./lib/grammar').parser.generate()\n dir = options.output or 'lib'\n fs.writeFile \"#{dir}/parser.js\", code"</script><div class='minibutton load' onclick='javascript: loadConsole(example42);'>load</div><br class='clear' /></div>
<p>
If you need to invoke one task before another &mdash; for example, running
<tt>build</tt> before <tt>test</tt>, you can use the <tt>invoke</tt> function:
<tt>invoke 'build'</tt>. Cake tasks are a minimal way to expose your
CoffeeScript functions to the command line, so
<a href="documentation/docs/cake.html">don't expect any fanciness built-in</a>.
If you need dependencies, or async callbacks, it's best to put them in your
code itself &mdash; not the cake task.
</p>
<h2>
<span id="source-maps" class="bookmark"></span>
Source Maps
</h2>
<p>
CoffeeScript 1.6.1 and above include support for generating source maps,
a way to tell your JavaScript engine what part of your CoffeeScript
program matches up with the code being evaluated. Browsers that support it
can automatically use source maps to show your original source code
in the debugger. To generate source maps alongside your JavaScript files,
pass the <tt>--map</tt> or <tt>-m</tt> flag to the compiler.
</p>
<p>
For a full introduction to source maps, how they work, and how to hook
them up in your browser, read the
<a href="http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/">HTML5 Tutorial</a>.
</p>
<h2>
<span id="scripts" class="bookmark"></span>
"text/coffeescript" Script Tags
</h2>
<p>
While it's not recommended for serious use, CoffeeScripts may be included
directly within the browser using <tt>&lt;script type="text/coffeescript"&gt;</tt>
tags. The source includes a compressed and minified version of the compiler
(<a href="extras/coffee-script.js">Download current version here, 39k when gzipped</a>)
as <tt>extras/coffee-script.js</tt>. Include this file on a page with
inline CoffeeScript tags, and it will compile and evaluate them in order.
</p>
<p>
In fact, the little bit of glue script that runs "Try CoffeeScript" above,
as well as the 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 <tt>CoffeeScript.compile()</tt>
so you can pop open Firebug and try compiling some strings.
</p>
<p>
The usual caveats about CoffeeScript apply &mdash; your inline scripts will
run within a closure wrapper, so if you want to expose global variables or
functions, attach them to the <tt>window</tt> object.
</p>
<h2>
<span id="resources" class="bookmark"></span>
Books
</h2>
<p>
There are a number of excellent resources to help you get
started with CoffeeScript, some of which are freely available online.
</p>
<ul>
<li>
<a href="http://arcturo.github.com/library/coffeescript/">The Little Book on CoffeeScript</a>
is a brief 5-chapter introduction to CoffeeScript, written with great
clarity and precision by
<a href="http://alexmaccaw.co.uk/">Alex MacCaw</a>.
</li>
<li>
<a href="http://autotelicum.github.com/Smooth-CoffeeScript/">Smooth CoffeeScript</a>
is a reimagination of the excellent book
<a href="http://eloquentjavascript.net/">Eloquent JavaScript</a>, as if
it had been written in CoffeeScript instead. Covers language features
as well as the functional and object oriented programming styles. By
<a href="https://github.com/autotelicum">E. Hoigaard</a>.
</li>
<li>
<a href="http://pragprog.com/book/tbcoffee/coffeescript">CoffeeScript: Accelerated JavaScript Development</a>
is <a href="http://trevorburnham.com/">Trevor Burnham</a>'s thorough
introduction to the language. By the end of the book, you'll have built
a fast-paced multiplayer word game, writing both the client-side and Node.js
portions in CoffeeScript.
</li>
<li>
<a href="http://www.packtpub.com/coffeescript-programming-with-jquery-rails-nodejs/book">CoffeeScript Programming with jQuery, Rails, and Node.js</a>
is a new book by Michael Erasmus that covers CoffeeScript with an eye
towards real-world usage both in the browser (jQuery) and on the server
size (Rails, Node).
</li>
<li>
<a href="https://leanpub.com/coffeescript-ristretto/read">CoffeeScript Ristretto</a>
is a deep dive into CoffeeScript's semantics from simple functions up through
closures, higher-order functions, objects, classes, combinators, and decorators.
By <a href="http://braythwayt.com/">Reg Braithwaite</a>.
</li>
<li>
<a href="https://efendibooks.com/minibooks/testing-with-coffeescript">Testing with CoffeeScript</a>
is a succinct and freely downloadable guide to building testable
applications with CoffeeScript and Jasmine.
</li>
<li>
<a href="http://www.packtpub.com/coffeescript-application-development/book">CoffeeScript Application Development</a>
is a new book from Packt Publishing that introduces CoffeeScript while
walking through the process of building a demonstration web application.
</li>
<li>
<a href="http://www.manning.com/lee/">CoffeeScript in Action</a>
is a new book from Manning Publications that covers CoffeeScript syntax, composition techniques
and application development.
</li>
</ul>
<h2>
Screencasts
</h2>
<ul>
<li>
<a href="http://coffeescript.codeschool.com">A Sip of CoffeeScript</a> is a <a href="http://www.codeschool.com">Code School Course</a>
which combines 6 screencasts with in-browser coding to make learning fun. The first level is free to try out.
</li>
<li>
<a href="http://peepcode.com/products/coffeescript">Meet CoffeeScript</a>
is a 75-minute long screencast by <a href="http://peepcode.com/">PeepCode</a>.
Highly memorable for its animations which demonstrate transforming CoffeeScript
into the equivalent JS.
</li>
<li>
If you're looking for less of a time commitment, RailsCasts'
<a href="http://railscasts.com/episodes/267-coffeescript-basics">CoffeeScript Basics</a>
should have you covered, hitting all of the important notes about CoffeeScript
in 11 minutes.
</li>
</ul>
<h2>
Examples
</h2>
<p>
The <a href="https://github.com/trending?l=coffeescript&amp;since=monthly">best list of
open-source CoffeeScript examples</a> can be found on GitHub. But just
to throw out few more:
</p>
<ul>
<li>
<b>github</b>'s <a href="http://hubot.github.com/">Hubot</a>,
a friendly IRC robot that can perform any number of useful and useless tasks.
</li>
<li>
<b>sstephenson</b>'s <a href="http://pow.cx/">Pow</a>,
a zero-configuration Rack server, with comprehensive annotated source.
</li>
<li>
<b>technoweenie</b>'s <a href="https://github.com/technoweenie/coffee-resque">Coffee-Resque</a>,
a port of <a href="https://github.com/defunkt/resque">Resque</a> for Node.js.
</li>
<li>
<b>assaf</b>'s <a href="http://zombie.labnotes.org/">Zombie.js</a>,
a headless, full-stack, faux-browser testing library for Node.js.
</li>
<li>
<b>jashkenas</b>' <a href="documentation/docs/underscore.html">Underscore.coffee</a>, a port
of the <a href="http://documentcloud.github.com/underscore/">Underscore.js</a>
library of helper functions.
</li>
<li>
<b>stephank</b>'s <a href="https://github.com/stephank/orona">Orona</a>, a remake of
the Bolo tank game for modern browsers.
</li>
<li>
<b>github</b>'s <a href="https://atom.io/">Atom</a>,
a hackable text editor built on web technologies.
</li>
</ul>
<h2>
Resources
</h2>
<ul>
<li>
<a href="http://github.com/jashkenas/coffeescript/">Source Code</a><br />
Use <tt>bin/coffee</tt> to test your changes,<br />
<tt>bin/cake test</tt> to run the test suite,<br />
<tt>bin/cake build</tt> to rebuild the CoffeeScript compiler, and <br />
<tt>bin/cake build:parser</tt> to regenerate the Jison parser if you're
working on the grammar. <br /><br />
<tt>git checkout lib &amp;&amp; bin/cake build:full</tt> is a good command to run when you're working
on the core language. It'll refresh the lib directory
(in case you broke something), build your altered compiler, use that to
rebuild itself (a good sanity test) and then run all of the tests. If
they pass, there's a good chance you've made a successful change.
</li>
<li>
<a href="http://github.com/jashkenas/coffeescript/issues">CoffeeScript Issues</a><br />
Bug reports, feature proposals, and ideas for changes to the language belong here.
</li>
<li>
<a href="https://groups.google.com/forum/#!forum/coffeescript">CoffeeScript Google Group</a><br />
If you'd like to ask a question, the mailing list is a good place to get help.
</li>
<li>
<a href="http://github.com/jashkenas/coffeescript/wiki">The CoffeeScript Wiki</a><br />
If you've ever learned a neat CoffeeScript tip or trick, or ran into a gotcha &mdash; share it on the wiki.
The wiki also serves as a directory of handy
<a href="http://github.com/jashkenas/coffeescript/wiki/Text-editor-plugins">text editor extensions</a>,
<a href="http://github.com/jashkenas/coffeescript/wiki/Web-framework-plugins">web framework plugins</a>,
and general <a href="http://github.com/jashkenas/coffeescript/wiki/Build-tools">CoffeeScript build tools</a>.
</li>
<li>
<a href="http://github.com/jashkenas/coffeescript/wiki/FAQ">The FAQ</a><br />
Perhaps your CoffeeScript-related question has been asked before. Check the FAQ first.
</li>
<li>
<a href="http://js2coffee.org">JS2Coffee</a><br />
Is a very well done reverse JavaScript-to-CoffeeScript compiler. It's
not going to be perfect (infer what your JavaScript classes are, when
you need bound functions, and so on...) &mdash; but it's a great starting
point for converting simple scripts.
</li>
<li>
<a href="https://github.com/jashkenas/coffeescript/downloads">High-Rez Logo</a><br />
The CoffeeScript logo is available in Illustrator, EPS and PSD formats, for use
in presentations.
</li>
</ul>
<h2>
<span id="webchat" class="bookmark"></span>
Web Chat (IRC)
</h2>
<p>
Quick help and advice can usually be found in the CoffeeScript IRC room.
Join <tt>#coffeescript</tt> on <tt>irc.freenode.net</tt>, or click the
button below to open a webchat session on this page.
</p>
<p>
<button id="open_webchat">click to open #coffeescript</button>
</p>
<h2>
<span id="changelog" class="bookmark"></span>
Change Log
</h2>
<p>
<div class="anchor" id="1.8.0"></div>
<b class="header">
<a href="https://github.com/jashkenas/coffeescript/compare/1.7.1...1.8.0">1.8.0</a>
<span class="timestamp"> &mdash; <time datetime="2014-08-26">August 26, 2014</time></span>
</b>
<ul>
<li>
The <tt>--join</tt> option of the CLI is now deprecated.
</li>
<li>
Source maps now use <tt>.js.map</tt> as file extension, instead of just <tt>.map</tt>.
</li>
<li>
The CLI now exits with the exit code 1 when it fails to write a file to disk.
</li>
<li>
The compiler no longer crashes on unterminated, single-quoted strings.
</li>
<li>
Fixed location data for string interpolations, which made source maps out of sync.
</li>
<li>
The error marker in error messages is now correctly positioned if the code is indented with tabs.
</li>
<li>
Fixed a slight formatting error in CoffeeScript’s source map-patched stack traces.
</li>
<li>
The <tt>%%</tt> operator now coerces its right operand only once.
</li>
<li>
It is now possible to require CoffeeScript files from Cakefiles without having to register the compiler first.
</li>
<li>
The CoffeeScript REPL is now exported and can be required using <tt>require 'coffee-script/repl'</tt>.
</li>
<li>
Fixes for the REPL in Node 0.11.
</li>
</ul>
</p>
<p>
<div class="anchor" id="1.7.1"></div>
<b class="header">
<a href="https://github.com/jashkenas/coffeescript/compare/1.7.0...1.7.1">1.7.1</a>
<span class="timestamp"> &mdash; <time datetime="2014-01-29">January 29, 2014</time></span>
</b>
<ul>
<li>
Fixed a typo that broke node module lookup when running a script directly with the <tt>coffee</tt> binary.
</li>
</ul>
</p>
<p>
<div class="anchor" id="1.7.0"></div>
<b class="header">
<a href="https://github.com/jashkenas/coffeescript/compare/1.6.3...1.7.0">1.7.0</a>
<span class="timestamp"> &mdash; <time datetime="2014-01-28">January 28, 2014</time></span>
</b>
<ul>
<li>
When requiring CoffeeScript files in Node you must now explicitly register the compiler. This can be done with <tt>require 'coffee-script/register'</tt> or <tt>CoffeeScript.register()</tt>. Also for configuration such as Mocha's, use <b>coffee-script/register</b>.
</li>
<li>
Improved error messages, source maps and stack traces. Source maps now use the updated <tt>//#</tt> syntax.
</li>
<li>
Leading <tt>.</tt> now closes all open calls, allowing for simpler chaining syntax.
</li>
</ul>
<div class='code'><pre><code>$ <span class="string">'body'</span>
.click <span class="function"><span class="params">(e)</span> -&gt;</span>
$ <span class="string">'.box'</span>
.fadeIn <span class="string">'fast'</span>
.addClass <span class="string">'.active'</span>
.css <span class="string">'background'</span>, <span class="string">'white'</span>
</code></pre><pre><code>$(<span class="string">'body'</span>).click(<span class="function"><span class="keyword">function</span><span class="params">(e)</span> {</span>
<span class="keyword">return</span> $(<span class="string">'.box'</span>).fadeIn(<span class="string">'fast'</span>).addClass(<span class="string">'.active'</span>);
}).css(<span class="string">'background'</span>, <span class="string">'white'</span>);
</code></pre><script>window.example43 = "$ 'body'\n.click (e) ->\n $ '.box'\n .fadeIn 'fast'\n .addClass '.active'\n.css 'background', 'white'\n\n\n"</script><div class='minibutton load' onclick='javascript: loadConsole(example43);'>load</div><br class='clear' /></div>
<ul>
<li>
Added <tt>**</tt>, <tt>//</tt> and <tt>%%</tt> operators and <tt>...</tt> expansion in parameter lists and destructuring expressions.
</li>
<li>
Multiline strings are now joined by a single space and ignore all indentation. A backslash at the end of a line can denote the amount of whitespace between lines, in both strings and heredocs. Backslashes correctly escape whitespace in block regexes.
</li>
<li>
Closing brackets can now be indented and therefore no longer cause unexpected error.
</li>
<li>
Several breaking compilation fixes. Non-callable literals (strings, numbers etc.) don't compile in a call now and multiple postfix conditionals compile properly. Postfix conditionals and loops always bind object literals. Conditional assignment compiles properly in subexpressions. <tt>super</tt> is disallowed outside of methods and works correctly inside <tt>for</tt> loops.
</li>
<li>
Formatting of compiled block comments has been improved.
</li>
<li>
No more <tt>-p</tt> folders on Windows.
</li>
<li>
The <tt>options</tt> object passed to CoffeeScript is no longer mutated.
</li>
</ul>
</p>
<p>
<div class="anchor" id="1.6.3"></div>
<b class="header">
<a href="https://github.com/jashkenas/coffeescript/compare/1.6.2...1.6.3">1.6.3</a>
<span class="timestamp"> &mdash; <time datetime="2013-06-02">June 2, 2013</time></span>
</b>
<ul>
<li>
The CoffeeScript REPL now remembers your history between sessions.
Just like a proper REPL should.
</li>
<li>
You can now use <tt>require</tt> in Node to load <tt>.coffee.md</tt>
Literate CoffeeScript files. In the browser,
<tt>text/literate-coffeescript</tt> script tags.
</li>
<li>
The old <tt>coffee --lint</tt> command has been removed. It was useful
while originally working on the compiler, but has been surpassed by
JSHint. You may now use <tt>-l</tt> to pass literate files in over
<b>stdio</b>.
</li>
<li>
Bugfixes for Windows path separators, <tt>catch</tt> without naming
the error, and executable-class-bodies-with-
prototypal-property-attachment.
</li>
</ul>
</p>
<p>
<div class="anchor" id="1.6.2"></div>
<b class="header">
<a href="https://github.com/jashkenas/coffeescript/compare/1.6.1...1.6.2">1.6.2</a>
<span class="timestamp"> &mdash; <time datetime="2013-03-18">March 18, 2013</time></span>
</b>
<ul>
<li>
Source maps have been used to provide automatic line-mapping when
running CoffeeScript directly via the <tt>coffee</tt> command, and
for automatic line-mapping when running CoffeeScript directly in the
browser. Also, to provide better error messages for semantic errors
thrown by the compiler &mdash;
<a href="http://cl.ly/NdOA">with colors, even</a>.
</li>
<li>
Improved support for mixed literate/vanilla-style CoffeeScript projects,
and generating source maps for both at the same time.
</li>
<li>
Fixes for <b>1.6.x</b> regressions with overriding inherited bound