1
0
Fork 0
mirror of https://github.com/jashkenas/coffeescript.git synced 2022-11-09 12:23:24 -05:00
jashkenas--coffeescript/index.html
2010-11-21 21:21:07 -05:00

2291 lines
132 KiB
HTML

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=UTF-8" />
<title>CoffeeScript</title>
<link rel="stylesheet" type="text/css" href="documentation/css/docs.css" />
<link rel="stylesheet" type="text/css" href="documentation/css/idle.css" />
<link rel="shortcut icon" href="documentation/images/favicon.ico" />
</head>
<body class="minimized">
<div id="fadeout"></div>
<div id="flybar">
<a id="logo" href="#top"> </a>
<div class="navigation toc">
<div class="button">
Table of Contents
</div>
<div class="contents">
<a href="#overview">Overview</a>
<a href="#installation">Installation and Usage</a>
<a href="#language">Language Reference</a>
<a href="#whitespace">Significant Whitespace</a>
<a href="#functions">Functions and Invocation</a>
<a href="#objects_and_arrays">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="#aliases">Aliases</a>
<a href="#splats">Splats...</a>
<a href="#while">While, Until, and Loop</a>
<a href="#comprehensions">Comprehensions (Arrays, Objects, and Ranges)</a>
<a href="#expressions">Everything is an Expression</a>
<a href="#existence">The Existential Operator</a>
<a href="#classes">Classes, Inheritance, and Super</a>
<a href="#pattern_matching">Pattern Matching</a>
<a href="#fat_arrow">Function Binding</a>
<a href="#embedded">Embedded JavaScript</a>
<a href="#switch">The Switch Statement</a>
<a href="#try">Try/Catch/Finally</a>
<a href="#comparisons">Chained Comparisons</a>
<a href="#strings">String Interpolation, Heredocs, and Block Comments</a>
<a href="#regexes">Extended Regular Expressions</a>
<a href="#cake">Cake, and Cakefiles</a>
<a href="#scripts">"text/coffeescript" Script Tags</a>
<a href="#examples">Examples</a>
<a href="#resources">Resources</a>
<a href="#webchat">Web Chat (IRC)</a>
<a href="#change_log">Change Log</a>
</div>
</div>
<div class="navigation try">
<div class="button">
Try CoffeeScript
</div>
<div class="contents repl_wrapper">
<div class="code">
<div id="repl_source_wrap"><textarea id="repl_source" rows="100">alert "Hello CoffeeScript!"</textarea></div>
<pre id="repl_results"></pre>
<button class="full_screen">go full screen</button>
<button class="minimize">minimize</button>
<button class="run">run</button>
<br class="clear" />
</div>
</div>
</div>
<div class="navigation annotated">
<div class="button">
Annotated Source
</div>
<div class="contents">
<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>
</div>
</div>
<div id="error" style="display:none;"></div>
</div>
<div class="container">
<span class="bookmark" id="top"></span>
<p>
CoffeeScript is a little language that compiles into JavaScript. Underneath
all of those embarrassing braces and semicolons, JavaScript has always had
a gorgeous object model at its 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 (and vice-versa). The compiled output is readable and pretty-printed,
passes through <a href="http://www.javascriptlint.com/">JavaScript Lint</a>
without warnings, and can be run by any JavaScript implementation.
</p>
<p>
<b>Latest Version:</b>
<a href="http://github.com/jashkenas/coffee-script/tarball/0.9.5">0.9.5</a>
</p>
<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 class="idle"><span class="Comment"><span class="Comment">#</span> Assignment:</span>
number <span class="Keyword">=</span> <span class="Number">42</span>
opposite <span class="Keyword">=</span> <span class="BuiltInConstant">true</span>
<span class="Comment"><span class="Comment">#</span> Conditions:</span>
number <span class="Keyword">=</span> <span class="Keyword">-</span><span class="Number">42</span> <span class="Keyword">if</span> opposite
<span class="Comment"><span class="Comment">#</span> Functions:</span>
<span class="FunctionName">square </span><span class="Keyword">=</span> <span class="FunctionArgument">(x)</span> <span class="Storage">-&gt;</span> x <span class="Keyword">*</span> x
<span class="Comment"><span class="Comment">#</span> Arrays:</span>
list <span class="Keyword">=</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="Comment"><span class="Comment">#</span> Objects:</span>
math <span class="Keyword">=</span>
root: Math.sqrt
square: square
<span class="FunctionName">cube</span><span class="Keyword">:</span> <span class="FunctionArgument">(x)</span> <span class="Storage">-&gt;</span> x <span class="Keyword">*</span> square x
<span class="Comment"><span class="Comment">#</span> Splats:</span>
<span class="FunctionName">race </span><span class="Keyword">=</span> <span class="FunctionArgument">(winner, runners...)</span> <span class="Storage">-&gt;</span>
print winner, runners
<span class="Comment"><span class="Comment">#</span> Existence:</span>
alert <span class="String"><span class="String">&quot;</span>I knew it!<span class="String">&quot;</span></span> <span class="Keyword">if</span> elvis<span class="Keyword">?</span>
<span class="Comment"><span class="Comment">#</span> Array comprehensions:</span>
cubes <span class="Keyword">=</span> (math.cube num <span class="Keyword">for</span> num <span class="Keyword">in</span> list)
</pre><pre class="idle"><span class="Storage">var</span> cubes, list, math, num, number, opposite, race, square, _i, _len, _results;
<span class="Storage">var</span> __slice <span class="Keyword">=</span> <span class="LibraryClassType">Array</span>.<span class="LibraryConstant">prototype</span>.slice;
number <span class="Keyword">=</span> <span class="Number">42</span>;
opposite <span class="Keyword">=</span> <span class="BuiltInConstant">true</span>;
<span class="Keyword">if</span> (opposite) {
number <span class="Keyword">=</span> <span class="Keyword">-</span><span class="Number">42</span>;
}
<span class="FunctionName">square</span> = <span class="Storage">function</span>(<span class="FunctionArgument">x</span>) {
<span class="Keyword">return</span> x <span class="Keyword">*</span> x;
};
list <span class="Keyword">=</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>];
math <span class="Keyword">=</span> {
root: <span class="LibraryClassType">Math</span>.sqrt,
square: square,
<span class="FunctionName">cube</span>: <span class="Storage">function</span>(<span class="FunctionArgument">x</span>) {
<span class="Keyword">return</span> x <span class="Keyword">*</span> square(x);
}
};
<span class="FunctionName">race</span> = <span class="Storage">function</span>() {
<span class="Storage">var</span> runners, winner;
winner <span class="Keyword">=</span> arguments[<span class="Number">0</span>], runners <span class="Keyword">=</span> <span class="Number">2</span> <span class="Keyword">&lt;=</span> arguments.<span class="LibraryConstant">length</span> ? __slice.<span class="LibraryFunction">call</span>(arguments, <span class="Number">1</span>) : [];
<span class="Keyword">return</span> <span class="LibraryFunction">print</span>(winner, runners);
};
<span class="Keyword">if</span> (<span class="Keyword">typeof</span> elvis <span class="Keyword">!</span><span class="Keyword">=</span> <span class="String"><span class="String">&quot;</span>undefined<span class="String">&quot;</span></span> <span class="Keyword">&amp;</span><span class="Keyword">&amp;</span> elvis <span class="Keyword">!</span><span class="Keyword">==</span> <span class="BuiltInConstant">null</span>) {
<span class="LibraryFunction">alert</span>(<span class="String"><span class="String">&quot;</span>I knew it!<span class="String">&quot;</span></span>);
}
cubes <span class="Keyword">=</span> (<span class="Storage">function</span>() {
_results <span class="Keyword">=</span> [];
<span class="Keyword">for</span> (_i <span class="Keyword">=</span> <span class="Number">0</span>, _len <span class="Keyword">=</span> list.<span class="LibraryConstant">length</span>; _i <span class="Keyword">&lt;</span> _len; _i<span class="Keyword">++</span>) {
num <span class="Keyword">=</span> list[_i];
_results.<span class="LibraryFunction">push</span>(math.cube(num));
}
<span class="Keyword">return</span> _results;
}());
</pre><button onclick='javascript: var cubes, list, math, num, number, opposite, race, square, _i, _len, _results;
var __slice = Array.prototype.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() {
_results = [];
for (_i = 0, _len = list.length; _i < _len; _i++) {
num = list[_i];
_results.push(math.cube(num));
}
return _results;
}());;alert(cubes);'>run: cubes</button><br class='clear' /></div>
<h2>
<span id="installation" class="bookmark"></span>
Installation and Usage
</h2>
<p>
The CoffeeScript compiler
<a href="documentation/docs/grammar.html">is itself 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 core compiler 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 tagged 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 with NPM:
</p>
<pre>
npm install coffee-script</pre>
<p>
If you'd prefer to install the latest master version of CoffeeScript, you
can clone the CoffeeScript
<a href="http://github.com/jashkenas/coffee-script">source repository</a>
from GitHub, or download
<a href="http://github.com/jashkenas/coffee-script/tarball/master">the source</a> directly.
To install the CoffeeScript compiler system-wide
under <tt>/usr/local</tt>, open the directory and run:
</p>
<pre>
sudo bin/cake install</pre>
<p>
Both of these provide the <tt>coffee</tt> command, which can execute
coffee scripts, compile <tt>.coffee</tt> files into <tt>.js</tt>, and
provides 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 width="25%"><code>-i, --interactive</code></td>
<td>
Launch an interactive CoffeeScript session to try short snippets.
More pleasant if wrapped with
<a href="http://utopia.knoware.nl/~hlub/uck/rlwrap/rlwrap.html">rlwrap</a>.
</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>-w, --watch</code></td>
<td>
Watch the modification times of the coffee-scripts, recompiling as
soon as a change occurs.
</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>-l, --lint</code></td>
<td>
If the <tt>jsl</tt>
(<a href="http://www.javascriptlint.com/">JavaScript Lint</a>)
command is installed, use it
to check the compilation of a CoffeeScript file. (Handy in
conjunction with <br /> <tt>--watch</tt>)
</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>-e, --eval</code></td>
<td>
Compile and print a little snippet of CoffeeScript directly from the
command line. For example:<br /><tt>coffee -e "puts num for num in [10..1]"</tt>
</td>
</tr>
<tr>
<td><code>-r, --require</code></td>
<td>
Load a library before compiling or executing your script. Can be used
to hook in to the compiler (to add Growl notifications, for example).
</td>
</tr>
<tr>
<td><code>-b, --bare</code></td>
<td>
Compile the JavaScript without the top-level function safety wrapper.
(Used for CoffeeScript as a Node.js module.)
</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>
</table>
<p>
<b>Examples:</b>
</p>
<pre>
coffee -o lib/ -c src/
coffee --watch --lint experimental.coffee
coffee --print app/scripts/*.coffee > concatenation.js
coffee --bare --print --stdio</pre>
<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 "run"
button towards the bottom right. You can also paste examples into
"Try CoffeeScript" in the toolbar, and play with them from there.
</i>
<p>
<span id="whitespace" class="bookmark"></span>
<b class="header">Significant Whitespace</b>
CoffeeScript uses Python-style significant whitespace: You don't need to
use semicolons <tt>;</tt> to terminate expressions, ending
the line will do just as well. Semicolons can still be used to fit
multiple expressions onto a single line. Instead of using curly braces
<tt>{ }</tt> to delimit blocks of code (like <a href="#functions">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:<br /><tt>print "coffee"</tt>. The implicit call wraps forward
to the end of the line or block expression.
</p>
<p>
Within object literals, indentation can be used to create nested objects.
</p>
<p>
<span id="functions" class="bookmark"></span>
<b class="header">Functions</b>
Functions are defined by a list of parameters, an arrow, and the
function body. The empty function looks like this: <tt>-></tt>
</p>
<div class='code'><pre class="idle"><span class="FunctionName">square </span><span class="Keyword">=</span> <span class="FunctionArgument">(x)</span> <span class="Storage">-&gt;</span> x <span class="Keyword">*</span> x
<span class="FunctionName">cube </span><span class="Keyword">=</span> <span class="FunctionArgument">(x)</span> <span class="Storage">-&gt;</span> square(x) <span class="Keyword">*</span> x
</pre><pre class="idle"><span class="Storage">var</span> cube, square;
<span class="FunctionName">square</span> = <span class="Storage">function</span>(<span class="FunctionArgument">x</span>) {
<span class="Keyword">return</span> x <span class="Keyword">*</span> x;
};
<span class="FunctionName">cube</span> = <span class="Storage">function</span>(<span class="FunctionArgument">x</span>) {
<span class="Keyword">return</span> square(x) <span class="Keyword">*</span> x;
};
</pre><button onclick='javascript: var cube, square;
square = function(x) {
return x * x;
};
cube = function(x) {
return square(x) * x;
};;alert(cube(5));'>run: cube(5)</button><br class='clear' /></div>
<p>
Functions may also have default values for arguments.
</p>
<div class='code'><pre class="idle"><span class="FunctionName">fill </span><span class="Keyword">=</span> <span class="FunctionArgument">(container, liquid = &quot;coffee&quot;)</span> <span class="Storage">-&gt;</span>
<span class="String"><span class="String">&quot;</span>Filling the <span class="String"><span class="String">#{</span>container<span class="String">}</span></span> with <span class="String"><span class="String">#{</span>liquid<span class="String">}</span></span>...<span class="String">&quot;</span></span>
</pre><pre class="idle"><span class="Storage">var</span> fill;
<span class="FunctionName">fill</span> = <span class="Storage">function</span>(<span class="FunctionArgument">container, liquid</span>) {
<span class="Keyword">if</span> (liquid <span class="Keyword">==</span> <span class="BuiltInConstant">null</span>) {
liquid <span class="Keyword">=</span> <span class="String"><span class="String">&quot;</span>coffee<span class="String">&quot;</span></span>;
}
<span class="Keyword">return</span> <span class="String"><span class="String">&quot;</span>Filling the <span class="String">&quot;</span></span> <span class="Keyword">+</span> container <span class="Keyword">+</span> <span class="String"><span class="String">&quot;</span> with <span class="String">&quot;</span></span> <span class="Keyword">+</span> liquid <span class="Keyword">+</span> <span class="String"><span class="String">&quot;</span>...<span class="String">&quot;</span></span>;
};
</pre><button 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")</button><br class='clear' /></div>
<p>
<span id="objects_and_arrays" class="bookmark"></span>
<b class="header">Objects and Arrays</b>
Object and Array literals 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 YAML.
</p>
<div class='code'><pre class="idle">song <span class="Keyword">=</span> [<span class="String"><span class="String">&quot;</span>do<span class="String">&quot;</span></span>, <span class="String"><span class="String">&quot;</span>re<span class="String">&quot;</span></span>, <span class="String"><span class="String">&quot;</span>mi<span class="String">&quot;</span></span>, <span class="String"><span class="String">&quot;</span>fa<span class="String">&quot;</span></span>, <span class="String"><span class="String">&quot;</span>so<span class="String">&quot;</span></span>]
singers <span class="Keyword">=</span> {Jagger: <span class="String"><span class="String">&quot;</span>Rock<span class="String">&quot;</span></span>, Elvis: <span class="String"><span class="String">&quot;</span>Roll<span class="String">&quot;</span></span>}
matrix <span class="Keyword">=</span> [
<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="Keyword">=</span>
brother:
name: <span class="String"><span class="String">&quot;</span>Max<span class="String">&quot;</span></span>
age: <span class="Number">11</span>
sister:
name: <span class="String"><span class="String">&quot;</span>Ida<span class="String">&quot;</span></span>
age: <span class="Number">9</span>
</pre><pre class="idle"><span class="Storage">var</span> kids, matrix, singers, song;
song <span class="Keyword">=</span> [<span class="String"><span class="String">&quot;</span>do<span class="String">&quot;</span></span>, <span class="String"><span class="String">&quot;</span>re<span class="String">&quot;</span></span>, <span class="String"><span class="String">&quot;</span>mi<span class="String">&quot;</span></span>, <span class="String"><span class="String">&quot;</span>fa<span class="String">&quot;</span></span>, <span class="String"><span class="String">&quot;</span>so<span class="String">&quot;</span></span>];
singers <span class="Keyword">=</span> {
Jagger: <span class="String"><span class="String">&quot;</span>Rock<span class="String">&quot;</span></span>,
Elvis: <span class="String"><span class="String">&quot;</span>Roll<span class="String">&quot;</span></span>
};
matrix <span class="Keyword">=</span> [<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="Keyword">=</span> {
brother: {
name: <span class="String"><span class="String">&quot;</span>Max<span class="String">&quot;</span></span>,
age: <span class="Number">11</span>
},
sister: {
name: <span class="String"><span class="String">&quot;</span>Ida<span class="String">&quot;</span></span>,
age: <span class="Number">9</span>
}
};
</pre><button onclick='javascript: var kids, matrix, singers, song;
song = ["do", "re", "mi", "fa", "so"];
singers = {
Jagger: "Rock",
Elvis: "Roll"
};
matrix = [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(",")</button><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 class="idle">$(<span class="String"><span class="String">'</span>.account<span class="String">'</span></span>).attr class: <span class="String"><span class="String">'</span>active<span class="String">'</span></span>
log object.class
</pre><pre class="idle"><span class="Keyword">$</span>(<span class="String"><span class="String">'</span>.account<span class="String">'</span></span>).attr({
<span class="String"><span class="String">&quot;</span>class<span class="String">&quot;</span></span>: <span class="String"><span class="String">'</span>active<span class="String">'</span></span>
});
<span class="LibraryFunction">log</span>(object[<span class="String"><span class="String">&quot;</span>class<span class="String">&quot;</span></span>]);
</pre><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 class="idle">outer <span class="Keyword">=</span> <span class="Number">1</span>
<span class="FunctionName">changeNumbers </span><span class="Keyword">=</span> <span class="Keyword">-</span><span class="Keyword">&gt;</span>
inner <span class="Keyword">=</span> <span class="Keyword">-</span><span class="Number">1</span>
outer <span class="Keyword">=</span> <span class="Number">10</span>
inner <span class="Keyword">=</span> changeNumbers()
</pre><pre class="idle"><span class="Storage">var</span> changeNumbers, inner, outer;
outer <span class="Keyword">=</span> <span class="Number">1</span>;
<span class="FunctionName">changeNumbers</span> = <span class="Storage">function</span>() {
<span class="Storage">var</span> inner;
inner <span class="Keyword">=</span> <span class="Keyword">-</span><span class="Number">1</span>;
<span class="Keyword">return</span> outer <span class="Keyword">=</span> <span class="Number">10</span>;
};
inner <span class="Keyword">=</span> changeNumbers();
</pre><button onclick='javascript: var changeNumbers, inner, outer;
outer = 1;
changeNumbers = function() {
var inner;
inner = -1;
return outer = 10;
};
inner = changeNumbers();;alert(inner);'>run: inner</button><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 class="idle">mood <span class="Keyword">=</span> 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">=</span> <span class="Keyword">if</span> friday <span class="Keyword">then</span> sue <span class="Keyword">else</span> jill
options <span class="Keyword">or=</span> defaults
</pre><pre class="idle"><span class="Storage">var</span> date, mood;
<span class="Keyword">if</span> (singing) {
mood <span class="Keyword">=</span> greatlyImproved;
}
<span class="Keyword">if</span> (happy <span class="Keyword">&amp;</span><span class="Keyword">&amp;</span> knowsIt) {
clapsHands();
chaChaCha();
} <span class="Keyword">else</span> {
showIt();
}
date <span class="Keyword">=</span> friday ? sue : jill;
options <span class="Keyword">||</span> (options <span class="Keyword">=</span> defaults);
</pre><br class='clear' /></div>
<p>
<span id="aliases" class="bookmark"></span>
<b class="header">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>
For single-line statements, <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>
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, yes, on</tt></td><td><tt>true</tt></td></tr>
<tr><td><tt>false, no, off</tt></td><td><tt>false</tt></td></tr>
<tr><td><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>(no JS equivalent)</td></tr>
</table>
<div class='code'><pre class="idle">launch() <span class="Keyword">if</span> ignition <span class="Keyword">is</span> <span class="BuiltInConstant">on</span>
volume <span class="Keyword">=</span> <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="BuiltInConstant">no</span>
<span class="Keyword">if</span> car.speed <span class="Keyword">&lt;</span> limit <span class="Keyword">then</span> accelerate()
winner <span class="Keyword">=</span> <span class="BuiltInConstant">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>]
print inspect <span class="String"><span class="String">&quot;</span>My name is <span class="String">&quot;</span></span> <span class="Keyword">+</span> <span class="Variable">@name</span>
</pre><pre class="idle"><span class="Storage">var</span> volume, winner;
<span class="Keyword">if</span> (ignition <span class="Keyword">===</span> <span class="BuiltInConstant">true</span>) {
launch();
}
<span class="Keyword">if</span> (band <span class="Keyword">!</span><span class="Keyword">==</span> SpinalTap) {
volume <span class="Keyword">=</span> <span class="Number">10</span>;
}
<span class="Keyword">if</span> (answer <span class="Keyword">!</span><span class="Keyword">==</span> <span class="BuiltInConstant">false</span>) {
letTheWildRumpusBegin();
}
<span class="Keyword">if</span> (car.speed <span class="Keyword">&lt;</span> limit) {
accelerate();
}
<span class="Keyword">if</span> (pick <span class="Keyword">===</span> <span class="Number">47</span> <span class="Keyword">||</span> pick <span class="Keyword">===</span> <span class="Number">92</span> <span class="Keyword">||</span> pick <span class="Keyword">===</span> <span class="Number">13</span>) {
winner <span class="Keyword">=</span> <span class="BuiltInConstant">true</span>;
}
<span class="LibraryFunction">print</span>(inspect(<span class="String"><span class="String">&quot;</span>My name is <span class="String">&quot;</span></span> <span class="Keyword">+</span> <span class="Variable">this</span>.<span class="LibraryConstant">name</span>));
</pre><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 class="idle">gold <span class="Keyword">=</span> silver <span class="Keyword">=</span> rest <span class="Keyword">=</span> <span class="String"><span class="String">&quot;</span>unknown<span class="String">&quot;</span></span>
<span class="FunctionName">awardMedals </span><span class="Keyword">=</span> <span class="FunctionArgument">(first, second, others...)</span> <span class="Storage">-&gt;</span>
gold <span class="Keyword">=</span> first
silver <span class="Keyword">=</span> second
rest <span class="Keyword">=</span> others
contenders <span class="Keyword">=</span> [
<span class="String"><span class="String">&quot;</span>Michael Phelps<span class="String">&quot;</span></span>
<span class="String"><span class="String">&quot;</span>Liu Xiang<span class="String">&quot;</span></span>
<span class="String"><span class="String">&quot;</span>Yao Ming<span class="String">&quot;</span></span>
<span class="String"><span class="String">&quot;</span>Allyson Felix<span class="String">&quot;</span></span>
<span class="String"><span class="String">&quot;</span>Shawn Johnson<span class="String">&quot;</span></span>
<span class="String"><span class="String">&quot;</span>Roman Sebrle<span class="String">&quot;</span></span>
<span class="String"><span class="String">&quot;</span>Guo Jingjing<span class="String">&quot;</span></span>
<span class="String"><span class="String">&quot;</span>Tyson Gay<span class="String">&quot;</span></span>
<span class="String"><span class="String">&quot;</span>Asafa Powell<span class="String">&quot;</span></span>
<span class="String"><span class="String">&quot;</span>Usain Bolt<span class="String">&quot;</span></span>
]
awardMedals contenders...
alert <span class="String"><span class="String">&quot;</span>Gold: <span class="String">&quot;</span></span> <span class="Keyword">+</span> gold
alert <span class="String"><span class="String">&quot;</span>Silver: <span class="String">&quot;</span></span> <span class="Keyword">+</span> silver
alert <span class="String"><span class="String">&quot;</span>The Field: <span class="String">&quot;</span></span> <span class="Keyword">+</span> rest
</pre><pre class="idle"><span class="Storage">var</span> awardMedals, contenders, gold, rest, silver;
<span class="Storage">var</span> __slice <span class="Keyword">=</span> <span class="LibraryClassType">Array</span>.<span class="LibraryConstant">prototype</span>.slice;
gold <span class="Keyword">=</span> silver <span class="Keyword">=</span> rest <span class="Keyword">=</span> <span class="String"><span class="String">&quot;</span>unknown<span class="String">&quot;</span></span>;
<span class="FunctionName">awardMedals</span> = <span class="Storage">function</span>() {
<span class="Storage">var</span> first, others, second;
first <span class="Keyword">=</span> arguments[<span class="Number">0</span>], second <span class="Keyword">=</span> arguments[<span class="Number">1</span>], others <span class="Keyword">=</span> <span class="Number">3</span> <span class="Keyword">&lt;=</span> arguments.<span class="LibraryConstant">length</span> ? __slice.<span class="LibraryFunction">call</span>(arguments, <span class="Number">2</span>) : [];
gold <span class="Keyword">=</span> first;
silver <span class="Keyword">=</span> second;
<span class="Keyword">return</span> rest <span class="Keyword">=</span> others;
};
contenders <span class="Keyword">=</span> [<span class="String"><span class="String">&quot;</span>Michael Phelps<span class="String">&quot;</span></span>, <span class="String"><span class="String">&quot;</span>Liu Xiang<span class="String">&quot;</span></span>, <span class="String"><span class="String">&quot;</span>Yao Ming<span class="String">&quot;</span></span>, <span class="String"><span class="String">&quot;</span>Allyson Felix<span class="String">&quot;</span></span>, <span class="String"><span class="String">&quot;</span>Shawn Johnson<span class="String">&quot;</span></span>, <span class="String"><span class="String">&quot;</span>Roman Sebrle<span class="String">&quot;</span></span>, <span class="String"><span class="String">&quot;</span>Guo Jingjing<span class="String">&quot;</span></span>, <span class="String"><span class="String">&quot;</span>Tyson Gay<span class="String">&quot;</span></span>, <span class="String"><span class="String">&quot;</span>Asafa Powell<span class="String">&quot;</span></span>, <span class="String"><span class="String">&quot;</span>Usain Bolt<span class="String">&quot;</span></span>];
awardMedals.<span class="LibraryFunction">apply</span>(awardMedals, contenders);
<span class="LibraryFunction">alert</span>(<span class="String"><span class="String">&quot;</span>Gold: <span class="String">&quot;</span></span> <span class="Keyword">+</span> gold);
<span class="LibraryFunction">alert</span>(<span class="String"><span class="String">&quot;</span>Silver: <span class="String">&quot;</span></span> <span class="Keyword">+</span> silver);
<span class="LibraryFunction">alert</span>(<span class="String"><span class="String">&quot;</span>The Field: <span class="String">&quot;</span></span> <span class="Keyword">+</span> rest);
</pre><button onclick='javascript: var awardMedals, contenders, gold, rest, silver;
var __slice = Array.prototype.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(awardMedals, contenders);
alert("Gold: " + gold);
alert("Silver: " + silver);
alert("The Field: " + rest);;'>run</button><br class='clear' /></div>
<p>
<span id="while" class="bookmark"></span>
<b class="header">While, Until, and Loop</b>
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 class="idle"><span class="Comment"><span class="Comment">#</span> Econ 101</span>
<span class="Keyword">if</span> <span class="Variable">this</span>.studyingEconomics
buy() <span class="Keyword">while</span> supply <span class="Keyword">&gt;</span> demand
sell() <span class="Keyword">until</span> supply <span class="Keyword">&gt;</span> demand
<span class="Comment"><span class="Comment">#</span> Nursery Rhyme</span>
num <span class="Keyword">=</span> <span class="Number">6</span>
lyrics <span class="Keyword">=</span> <span class="Keyword">while</span> num <span class="Keyword">-</span><span class="Keyword">=</span> <span class="Number">1</span>
num <span class="Keyword">+</span> <span class="String"><span class="String">&quot;</span> little monkeys, jumping on the bed.</span>
<span class="String"> One fell out and bumped his head.<span class="String">&quot;</span></span>
</pre><pre class="idle"><span class="Storage">var</span> lyrics, num, _results;
<span class="Keyword">if</span> (<span class="Variable">this</span>.studyingEconomics) {
<span class="Keyword">while</span> (supply <span class="Keyword">&gt;</span> demand) {
buy();
}
<span class="Keyword">while</span> (supply <span class="Keyword">&lt;=</span> demand) {
sell();
}
}
num <span class="Keyword">=</span> <span class="Number">6</span>;
<span class="FunctionName">lyrics</span> = <span class="Storage">function</span>() {
_results <span class="Keyword">=</span> [];
<span class="Keyword">while</span> (num <span class="Keyword">-</span><span class="Keyword">=</span> <span class="Number">1</span>) {
_results.<span class="LibraryFunction">push</span>(num <span class="Keyword">+</span> <span class="String"><span class="String">&quot;</span> little monkeys, jumping on the bed. One fell out and bumped his head.<span class="String">&quot;</span></span>);
}
<span class="Keyword">return</span> _results;
}();
</pre><button onclick='javascript: var lyrics, num, _results;
if (this.studyingEconomics) {
while (supply > demand) {
buy();
}
while (supply <= demand) {
sell();
}
}
num = 6;
lyrics = function() {
_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("\n"));'>run: lyrics.join("\n")</button><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>.
Other JavaScript loops, such as <b>for</b> loops and <b>do-while</b> loops
can be mimicked by variations on <b>loop</b>, but the hope is that you
won't need to do that with CoffeeScript, either because you're using
<b>each</b> (<b>forEach</b>) style iterators, or...
</p>
<p>
<span id="comprehensions" class="bookmark"></span>
<b class="header">Comprehensions (Arrays, Objects, and Ranges)</b>
For your looping needs, CoffeeScript provides array comprehensions
similar to Python's. They 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. They 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>.
</p>
<div class='code'><pre class="idle"><span class="Comment"><span class="Comment">#</span> Eat lunch.</span>
lunch <span class="Keyword">=</span> eat food <span class="Keyword">for</span> food <span class="Keyword">in</span> [<span class="String"><span class="String">'</span>toast<span class="String">'</span></span>, <span class="String"><span class="String">'</span>cheese<span class="String">'</span></span>, <span class="String"><span class="String">'</span>wine<span class="String">'</span></span>]
<span class="Comment"><span class="Comment">#</span> Naive collision detection.</span>
<span class="Keyword">for</span> roid, pos <span class="Keyword">in</span> asteroids
<span class="Keyword">for</span> roid2 <span class="Keyword">in</span> asteroids <span class="Keyword">when</span> roid <span class="Keyword">isnt</span> roid2
roid.explode() <span class="Keyword">if</span> roid.overlaps roid2
</pre><pre class="idle"><span class="Storage">var</span> food, lunch, pos, roid, roid2, _i, _j, _len, _len2, _len3, _ref;
_ref <span class="Keyword">=</span> [<span class="String"><span class="String">'</span>toast<span class="String">'</span></span>, <span class="String"><span class="String">'</span>cheese<span class="String">'</span></span>, <span class="String"><span class="String">'</span>wine<span class="String">'</span></span>];
<span class="Keyword">for</span> (_i <span class="Keyword">=</span> <span class="Number">0</span>, _len <span class="Keyword">=</span> _ref.<span class="LibraryConstant">length</span>; _i <span class="Keyword">&lt;</span> _len; _i<span class="Keyword">++</span>) {
food <span class="Keyword">=</span> _ref[_i];
lunch <span class="Keyword">=</span> eat(food);
}
<span class="Keyword">for</span> (pos <span class="Keyword">=</span> <span class="Number">0</span>, _len2 <span class="Keyword">=</span> asteroids.<span class="LibraryConstant">length</span>; pos <span class="Keyword">&lt;</span> _len2; pos<span class="Keyword">++</span>) {
roid <span class="Keyword">=</span> asteroids[pos];
<span class="Keyword">for</span> (_j <span class="Keyword">=</span> <span class="Number">0</span>, _len3 <span class="Keyword">=</span> asteroids.<span class="LibraryConstant">length</span>; _j <span class="Keyword">&lt;</span> _len3; _j<span class="Keyword">++</span>) {
roid2 <span class="Keyword">=</span> asteroids[_j];
<span class="Keyword">if</span> (roid <span class="Keyword">!</span><span class="Keyword">==</span> roid2) {
<span class="Keyword">if</span> (roid.overlaps(roid2)) {
roid.explode();
}
}
}
}
</pre><br class='clear' /></div>
<p>
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 class="idle">countdown <span class="Keyword">=</span> (num <span class="Keyword">for</span> num <span class="Keyword">in</span> [<span class="Number">10</span>..<span class="Number">1</span>])
</pre><pre class="idle"><span class="Storage">var</span> countdown, num, _results;
countdown <span class="Keyword">=</span> (<span class="Storage">function</span>() {
_results <span class="Keyword">=</span> [];
<span class="Keyword">for</span> (num <span class="Keyword">=</span> <span class="Number">10</span>; num <span class="Keyword">&gt;=</span> <span class="Number">1</span>; num<span class="Keyword">--</span>) {
_results.<span class="LibraryFunction">push</span>(num);
}
<span class="Keyword">return</span> _results;
}());
</pre><button onclick='javascript: var countdown, num, _results;
countdown = (function() {
_results = [];
for (num = 10; num >= 1; num--) {
_results.push(num);
}
return _results;
}());;alert(countdown);'>run: countdown</button><br class='clear' /></div>
<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 class="idle">yearsOld <span class="Keyword">=</span> max: <span class="Number">10</span>, ida: <span class="Number">9</span>, tim: <span class="Number">11</span>
ages <span class="Keyword">=</span> <span class="Keyword">for</span> child, age <span class="Keyword">of</span> yearsOld
child <span class="Keyword">+</span> <span class="String"><span class="String">&quot;</span> is <span class="String">&quot;</span></span> <span class="Keyword">+</span> age
</pre><pre class="idle"><span class="Storage">var</span> age, ages, child, yearsOld, _results;
<span class="Storage">var</span> __hasProp <span class="Keyword">=</span> <span class="LibraryClassType">Object</span>.<span class="LibraryConstant">prototype</span>.hasOwnProperty;
yearsOld <span class="Keyword">=</span> {
max: <span class="Number">10</span>,
ida: <span class="Number">9</span>,
tim: <span class="Number">11</span>
};
<span class="FunctionName">ages</span> = <span class="Storage">function</span>() {
_results <span class="Keyword">=</span> [];
<span class="Keyword">for</span> (child <span class="Keyword">in</span> yearsOld) {
<span class="Keyword">if</span> (<span class="Keyword">!</span>__hasProp.<span class="LibraryFunction">call</span>(yearsOld, child)) <span class="Keyword">continue</span>;
age <span class="Keyword">=</span> yearsOld[child];
_results.<span class="LibraryFunction">push</span>(child <span class="Keyword">+</span> <span class="String"><span class="String">&quot;</span> is <span class="String">&quot;</span></span> <span class="Keyword">+</span> age);
}
<span class="Keyword">return</span> _results;
}();
</pre><button onclick='javascript: var age, ages, child, yearsOld, _results;
var __hasProp = Object.prototype.hasOwnProperty;
yearsOld = {
max: 10,
ida: 9,
tim: 11
};
ages = function() {
_results = [];
for (child in yearsOld) {
if (!__hasProp.call(yearsOld, child)) continue;
age = yearsOld[child];
_results.push(child + " is " + age);
}
return _results;
}();;alert(ages.join(", "));'>run: ages.join(", ")</button><br class='clear' /></div>
<p>
By default, object comprehensions are safe, and use a <tt>hasOwnProperty</tt>
check to make sure that you're dealing with properties on the current
object. If you'd like the regular JavaScript <br /><tt>for (key in obj) ...</tt>
loop, for speed or for another reason, you can use <br />
<tt>for all key, value of object</tt> in CoffeeScript.
</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 class="idle"><span class="FunctionName">grade </span><span class="Keyword">=</span> <span class="FunctionArgument">(student)</span> <span class="Storage">-&gt;</span>
<span class="Keyword">if</span> student.excellentWork
<span class="String"><span class="String">&quot;</span>A+<span class="String">&quot;</span></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"><span class="String">&quot;</span>B<span class="String">&quot;</span></span> <span class="Keyword">else</span> <span class="String"><span class="String">&quot;</span>B-<span class="String">&quot;</span></span>
<span class="Keyword">else</span>
<span class="String"><span class="String">&quot;</span>C<span class="String">&quot;</span></span>
eldest <span class="Keyword">=</span> <span class="Keyword">if</span> <span class="Number">24</span> <span class="Keyword">&gt;</span> <span class="Number">21</span> <span class="Keyword">then</span> <span class="String"><span class="String">&quot;</span>Liz<span class="String">&quot;</span></span> <span class="Keyword">else</span> <span class="String"><span class="String">&quot;</span>Ike<span class="String">&quot;</span></span>
</pre><pre class="idle"><span class="Storage">var</span> eldest, grade;
<span class="FunctionName">grade</span> = <span class="Storage">function</span>(<span class="FunctionArgument">student</span>) {
<span class="Keyword">if</span> (student.excellentWork) {
<span class="Keyword">return</span> <span class="String"><span class="String">&quot;</span>A+<span class="String">&quot;</span></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"><span class="String">&quot;</span>B<span class="String">&quot;</span></span>;
} <span class="Keyword">else</span> {
<span class="Keyword">return</span> <span class="String"><span class="String">&quot;</span>B-<span class="String">&quot;</span></span>;
}
} <span class="Keyword">else</span> {
<span class="Keyword">return</span> <span class="String"><span class="String">&quot;</span>C<span class="String">&quot;</span></span>;
}
};
eldest <span class="Keyword">=</span> <span class="Number">24</span> <span class="Keyword">&gt;</span> <span class="Number">21</span> ? <span class="String"><span class="String">&quot;</span>Liz<span class="String">&quot;</span></span> : <span class="String"><span class="String">&quot;</span>Ike<span class="String">&quot;</span></span>;
</pre><button 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</button><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 class="idle">six <span class="Keyword">=</span> (one <span class="Keyword">=</span> <span class="Number">1</span>) <span class="Keyword">+</span> (two <span class="Keyword">=</span> <span class="Number">2</span>) <span class="Keyword">+</span> (three <span class="Keyword">=</span> <span class="Number">3</span>)
</pre><pre class="idle"><span class="Storage">var</span> one, six, three, two;
six <span class="Keyword">=</span> (one <span class="Keyword">=</span> <span class="Number">1</span>) <span class="Keyword">+</span> (two <span class="Keyword">=</span> <span class="Number">2</span>) <span class="Keyword">+</span> (three <span class="Keyword">=</span> <span class="Number">3</span>);
</pre><button onclick='javascript: var one, six, three, two;
six = (one = 1) + (two = 2) + (three = 3);;alert(six);'>run: six</button><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 class="idle"><span class="Comment"><span class="Comment">#</span> The first ten global properties.</span>
globals <span class="Keyword">=</span> (name <span class="Keyword">for</span> name <span class="Keyword">of</span> window)[<span class="Number">0</span>...<span class="Number">10</span>]
</pre><pre class="idle"><span class="Storage">var</span> globals, name, _results;
<span class="Storage">var</span> __hasProp <span class="Keyword">=</span> <span class="LibraryClassType">Object</span>.<span class="LibraryConstant">prototype</span>.hasOwnProperty;
globals <span class="Keyword">=</span> (<span class="Storage">function</span>() {
_results <span class="Keyword">=</span> [];
<span class="Keyword">for</span> (name <span class="Keyword">in</span> <span class="LibraryClassType">window</span>) {
<span class="Keyword">if</span> (<span class="Keyword">!</span>__hasProp.<span class="LibraryFunction">call</span>(<span class="LibraryClassType">window</span>, name)) <span class="Keyword">continue</span>;
_results.<span class="LibraryFunction">push</span>(name);
}
<span class="Keyword">return</span> _results;
}()).<span class="LibraryFunction">slice</span>(<span class="Number">0</span>, <span class="Number">10</span>);
</pre><button onclick='javascript: var globals, name, _results;
var __hasProp = Object.prototype.hasOwnProperty;
globals = (function() {
_results = [];
for (name in window) {
if (!__hasProp.call(window, name)) continue;
_results.push(name);
}
return _results;
}()).slice(0, 10);;alert(globals);'>run: globals</button><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 class="idle">alert(
<span class="Keyword">try</span>
nonexistent <span class="Keyword">/</span> <span class="BuiltInConstant">undefined</span>
<span class="Keyword">catch</span> error
<span class="String"><span class="String">&quot;</span>And the error is ... <span class="String">&quot;</span></span> <span class="Keyword">+</span> error
)
</pre><pre class="idle"><span class="LibraryFunction">alert</span>(<span class="Storage">function</span>() {
<span class="Keyword">try</span> {
<span class="Keyword">return</span> nonexistent / <span class="Storage">void</span> <span class="Number">0</span>;
} <span class="Keyword">catch</span> (error) {
<span class="Keyword">return</span> <span class="String"><span class="String">&quot;</span>And the error is ... <span class="String">&quot;</span></span> <span class="Keyword">+</span> error;
}
}());
</pre><button onclick='javascript: alert(function() {
try {
return nonexistent / void 0;
} catch (error) {
return "And the error is ... " + error;
}
}());;'>run</button><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="existence" class="bookmark"></span>
<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 class="idle">solipsism <span class="Keyword">=</span> <span class="BuiltInConstant">true</span> <span class="Keyword">if</span> mind<span class="Keyword">?</span> <span class="Keyword">and</span> <span class="Keyword">not</span> world<span class="Keyword">?</span>
speed <span class="Keyword">?</span><span class="Keyword">=</span> <span class="Number">140</span>
</pre><pre class="idle"><span class="Storage">var</span> solipsism;
<span class="Keyword">if</span> ((<span class="Keyword">typeof</span> mind <span class="Keyword">!</span><span class="Keyword">=</span> <span class="String"><span class="String">&quot;</span>undefined<span class="String">&quot;</span></span> <span class="Keyword">&amp;</span><span class="Keyword">&amp;</span> mind <span class="Keyword">!</span><span class="Keyword">==</span> <span class="BuiltInConstant">null</span>) <span class="Keyword">&amp;</span><span class="Keyword">&amp;</span> <span class="Keyword">!</span>(<span class="Keyword">typeof</span> world <span class="Keyword">!</span><span class="Keyword">=</span> <span class="String"><span class="String">&quot;</span>undefined<span class="String">&quot;</span></span> <span class="Keyword">&amp;</span><span class="Keyword">&amp;</span> world <span class="Keyword">!</span><span class="Keyword">==</span> <span class="BuiltInConstant">null</span>)) {
solipsism <span class="Keyword">=</span> <span class="BuiltInConstant">true</span>;
}
<span class="Keyword">typeof</span> speed <span class="Keyword">!</span><span class="Keyword">=</span> <span class="String"><span class="String">&quot;</span>undefined<span class="String">&quot;</span></span> <span class="Keyword">&amp;</span><span class="Keyword">&amp;</span> speed <span class="Keyword">!</span><span class="Keyword">==</span> <span class="BuiltInConstant">null</span> ? speed : speed <span class="Keyword">=</span> <span class="Number">140</span>;
</pre><button onclick='javascript: var solipsism;
if ((typeof mind != "undefined" && mind !== null) && !(typeof world != "undefined" && world !== null)) {
solipsism = true;
}
typeof speed != "undefined" && speed !== null ? speed : speed = 140;;alert(speed);'>run: speed</button><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 class="idle">zip <span class="Keyword">=</span> lottery.drawWinner<span class="Keyword">?</span>().address<span class="Keyword">?</span>.zipcode
</pre><pre class="idle"><span class="Storage">var</span> zip, _ref;
zip <span class="Keyword">=</span> <span class="Keyword">typeof</span> lottery.drawWinner <span class="Keyword">===</span> <span class="String"><span class="String">&quot;</span>function<span class="String">&quot;</span></span> ? (_ref <span class="Keyword">=</span> lottery.drawWinner().address) <span class="Keyword">!</span><span class="Keyword">=</span> <span class="BuiltInConstant">null</span> ? _ref.zipcode : <span class="Storage">void</span> <span class="Number">0</span> : <span class="Storage">void</span> <span class="Number">0</span>;
</pre><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 reflection. In the
example below for the first class, <tt>this.constructor.name is "Animal"</tt>.
</p>
<div class='code'><pre class="idle"><span class="Storage">class</span> <span class="TypeName">Animal</span>
<span class="FunctionName">constructor</span><span class="Keyword">:</span> <span class="FunctionArgument">(@name)</span> <span class="Storage">-&gt;</span>
<span class="FunctionName">move</span><span class="Keyword">:</span> <span class="FunctionArgument">(meters)</span> <span class="Storage">-&gt;</span>
alert <span class="Variable">@name</span> <span class="Keyword">+</span> <span class="String"><span class="String">&quot;</span> moved <span class="String">&quot;</span></span> <span class="Keyword">+</span> meters <span class="Keyword">+</span> <span class="String"><span class="String">&quot;</span>m.<span class="String">&quot;</span></span>
<span class="Storage">class</span> <span class="TypeName">Snake</span><span class="InheritedClass"> <span class="Keyword">extends</span> Animal</span>
<span class="FunctionName">move</span><span class="Keyword">:</span> <span class="Keyword">-</span><span class="Keyword">&gt;</span>
alert <span class="String"><span class="String">&quot;</span>Slithering...<span class="String">&quot;</span></span>
<span class="Variable">super</span> <span class="Number">5</span>
<span class="Storage">class</span> <span class="TypeName">Horse</span><span class="InheritedClass"> <span class="Keyword">extends</span> Animal</span>
<span class="FunctionName">move</span><span class="Keyword">:</span> <span class="Keyword">-</span><span class="Keyword">&gt;</span>
alert <span class="String"><span class="String">&quot;</span>Galloping...<span class="String">&quot;</span></span>
<span class="Variable">super</span> <span class="Number">45</span>
sam <span class="Keyword">=</span> <span class="Keyword">new</span> <span class="TypeName">Snake</span> <span class="String"><span class="String">&quot;</span>Sammy the Python<span class="String">&quot;</span></span>
tom <span class="Keyword">=</span> <span class="Keyword">new</span> <span class="TypeName">Horse</span> <span class="String"><span class="String">&quot;</span>Tommy the Palomino<span class="String">&quot;</span></span>
sam.move()
tom.move()
</pre><pre class="idle"><span class="Storage">var</span> Animal, Horse, Snake, sam, tom;
<span class="Storage">var</span> __hasProp <span class="Keyword">=</span> <span class="LibraryClassType">Object</span>.<span class="LibraryConstant">prototype</span>.hasOwnProperty, <span class="FunctionName">__extends</span> = <span class="Storage">function</span>(<span class="FunctionArgument">child, parent</span>) {
<span class="Keyword">for</span> (<span class="Storage">var</span> key <span class="Keyword">in</span> parent) { <span class="Keyword">if</span> (__hasProp.<span class="LibraryFunction">call</span>(parent, key)) child[key] <span class="Keyword">=</span> parent[key]; }
<span class="Storage">function</span> <span class="FunctionName">ctor</span>() { <span class="Variable">this</span>.<span class="LibraryConstant">constructor</span> <span class="Keyword">=</span> child; }
<span class="LibraryClassType">ctor</span>.<span class="LibraryConstant">prototype</span> = parent.<span class="LibraryConstant">prototype</span>;
<span class="LibraryClassType">child</span>.<span class="LibraryConstant">prototype</span> = <span class="Keyword">new</span> <span class="TypeName">ctor</span>;
child.__super__ <span class="Keyword">=</span> parent.<span class="LibraryConstant">prototype</span>;
<span class="Keyword">return</span> child;
};
<span class="FunctionName">Animal</span> = <span class="Storage">function</span>() {
<span class="Storage">function</span> <span class="FunctionName">Animal</span>(<span class="FunctionArgument">name</span>) {
<span class="Variable">this</span>.<span class="LibraryConstant">name</span> <span class="Keyword">=</span> name;
}
<span class="LibraryClassType">Animal</span>.<span class="LibraryConstant">prototype</span>.<span class="FunctionName">move</span> = <span class="Storage">function</span>(<span class="FunctionArgument">meters</span>) {
<span class="Keyword">return</span> <span class="LibraryFunction">alert</span>(<span class="Variable">this</span>.<span class="LibraryConstant">name</span> <span class="Keyword">+</span> <span class="String"><span class="String">&quot;</span> moved <span class="String">&quot;</span></span> <span class="Keyword">+</span> meters <span class="Keyword">+</span> <span class="String"><span class="String">&quot;</span>m.<span class="String">&quot;</span></span>);
};
<span class="Keyword">return</span> Animal;
}();
<span class="FunctionName">Snake</span> = <span class="Storage">function</span>() {
<span class="Storage">function</span> <span class="FunctionName">Snake</span>() {
Snake.__super__.<span class="LibraryConstant">constructor</span>.<span class="LibraryFunction">apply</span>(<span class="Variable">this</span>, arguments);
}
__extends(Snake, Animal);
<span class="LibraryClassType">Snake</span>.<span class="LibraryConstant">prototype</span>.<span class="FunctionName">move</span> = <span class="Storage">function</span>() {
<span class="LibraryFunction">alert</span>(<span class="String"><span class="String">&quot;</span>Slithering...<span class="String">&quot;</span></span>);
<span class="Keyword">return</span> Snake.__super__.move.<span class="LibraryFunction">call</span>(<span class="Variable">this</span>, <span class="Number">5</span>);
};
<span class="Keyword">return</span> Snake;
}();
<span class="FunctionName">Horse</span> = <span class="Storage">function</span>() {
<span class="Storage">function</span> <span class="FunctionName">Horse</span>() {
Horse.__super__.<span class="LibraryConstant">constructor</span>.<span class="LibraryFunction">apply</span>(<span class="Variable">this</span>, arguments);
}
__extends(Horse, Animal);
<span class="LibraryClassType">Horse</span>.<span class="LibraryConstant">prototype</span>.<span class="FunctionName">move</span> = <span class="Storage">function</span>() {
<span class="LibraryFunction">alert</span>(<span class="String"><span class="String">&quot;</span>Galloping...<span class="String">&quot;</span></span>);
<span class="Keyword">return</span> Horse.__super__.move.<span class="LibraryFunction">call</span>(<span class="Variable">this</span>, <span class="Number">45</span>);
};
<span class="Keyword">return</span> Horse;
}();
sam <span class="Keyword">=</span> <span class="Keyword">new</span> <span class="TypeName">Snake</span>(<span class="String"><span class="String">&quot;</span>Sammy the Python<span class="String">&quot;</span></span>);
tom <span class="Keyword">=</span> <span class="Keyword">new</span> <span class="TypeName">Horse</span>(<span class="String"><span class="String">&quot;</span>Tommy the Palomino<span class="String">&quot;</span></span>);
sam.move();
tom.move();
</pre><button onclick='javascript: var Animal, Horse, Snake, sam, tom;
var __hasProp = Object.prototype.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() {
function Snake() {
Snake.__super__.constructor.apply(this, arguments);
}
__extends(Snake, Animal);
Snake.prototype.move = function() {
alert("Slithering...");
return Snake.__super__.move.call(this, 5);
};
return Snake;
}();
Horse = function() {
function Horse() {
Horse.__super__.constructor.apply(this, arguments);
}
__extends(Horse, Animal);
Horse.prototype.move = function() {
alert("Galloping...");
return Horse.__super__.move.call(this, 45);
};
return Horse;
}();
sam = new Snake("Sammy the Python");
tom = new Horse("Tommy the Palomino");
sam.move();
tom.move();;'>run</button><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, <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 class="idle"><span class="FunctionName">String::dasherize </span><span class="Keyword">=</span> <span class="Keyword">-</span><span class="Keyword">&gt;</span>
<span class="Variable">this</span>.replace <span class="String">/_/g</span>, <span class="String"><span class="String">&quot;</span>-<span class="String">&quot;</span></span>
</pre><pre class="idle"><span class="LibraryClassType">String</span>.<span class="LibraryConstant">prototype</span>.<span class="FunctionName">dasherize</span> = <span class="Storage">function</span>() {
<span class="Keyword">return</span> <span class="Variable">this</span>.<span class="LibraryFunction">replace</span>(<span class="String"><span class="String">/</span>_<span class="String">/</span>g</span>, <span class="String"><span class="String">&quot;</span>-<span class="String">&quot;</span></span>);
};
</pre><button onclick='javascript: String.prototype.dasherize = function() {
return this.replace(/_/g, "-");
};;alert("one_two".dasherize());'>run: "one_two".dasherize()</button><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="pattern_matching" class="bookmark"></span>
<b class="header">Pattern Matching (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 class="idle">theBait <span class="Keyword">=</span> <span class="Number">1000</span>
theSwitch <span class="Keyword">=</span> <span class="Number">0</span>
<span class="Keyword">[</span>theBait, theSwitch<span class="Keyword">] =</span> [theSwitch, theBait]
</pre><pre class="idle"><span class="Storage">var</span> theBait, theSwitch, _ref;
theBait <span class="Keyword">=</span> <span class="Number">1000</span>;
theSwitch <span class="Keyword">=</span> <span class="Number">0</span>;
_ref <span class="Keyword">=</span> [theSwitch, theBait], theBait <span class="Keyword">=</span> _ref[<span class="Number">0</span>], theSwitch <span class="Keyword">=</span> _ref[<span class="Number">1</span>];
</pre><button onclick='javascript: var theBait, theSwitch, _ref;
theBait = 1000;
theSwitch = 0;
_ref = [theSwitch, theBait], theBait = _ref[0], theSwitch = _ref[1];;alert(theBait);'>run: theBait</button><br class='clear' /></div>
<p>
But it's also helpful for dealing with functions that return multiple
values.
</p>
<div class='code'><pre class="idle"><span class="FunctionName">weatherReport </span><span class="Keyword">=</span> <span class="FunctionArgument">(location)</span> <span class="Storage">-&gt;</span>
<span class="Comment"><span class="Comment">#</span> Make an Ajax request to fetch the weather...</span>
[location, <span class="Number">72</span>, <span class="String"><span class="String">&quot;</span>Mostly Sunny<span class="String">&quot;</span></span>]
<span class="Keyword">[</span>city, temp, forecast<span class="Keyword">] =</span> weatherReport <span class="String"><span class="String">&quot;</span>Berkeley, CA<span class="String">&quot;</span></span>
</pre><pre class="idle"><span class="Storage">var</span> city, forecast, temp, weatherReport, _ref;
<span class="FunctionName">weatherReport</span> = <span class="Storage">function</span>(<span class="FunctionArgument">location</span>) {
<span class="Keyword">return</span> [location, <span class="Number">72</span>, <span class="String"><span class="String">&quot;</span>Mostly Sunny<span class="String">&quot;</span></span>];
};
_ref <span class="Keyword">=</span> weatherReport(<span class="String"><span class="String">&quot;</span>Berkeley, CA<span class="String">&quot;</span></span>), city <span class="Keyword">=</span> _ref[<span class="Number">0</span>], temp <span class="Keyword">=</span> _ref[<span class="Number">1</span>], forecast <span class="Keyword">=</span> _ref[<span class="Number">2</span>];
</pre><button 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</button><br class='clear' /></div>
<p>
Pattern matching can be used with any depth of array and object nesting,
to help pull out deeply nested properties.
</p>
<div class='code'><pre class="idle">futurists <span class="Keyword">=</span>
sculptor: <span class="String"><span class="String">&quot;</span>Umberto Boccioni<span class="String">&quot;</span></span>
painter: <span class="String"><span class="String">&quot;</span>Vladimir Burliuk<span class="String">&quot;</span></span>
poet:
name: <span class="String"><span class="String">&quot;</span>F.T. Marinetti<span class="String">&quot;</span></span>
address: [
<span class="String"><span class="String">&quot;</span>Via Roma 42R<span class="String">&quot;</span></span>
<span class="String"><span class="String">&quot;</span>Bellagio, Italy 22021<span class="String">&quot;</span></span>
]
<span class="Keyword">{</span>poet: {name, address: [street, city]}<span class="Keyword">} =</span> futurists
</pre><pre class="idle"><span class="Storage">var</span> city, futurists, name, street, _ref, _ref2;
futurists <span class="Keyword">=</span> {
sculptor: <span class="String"><span class="String">&quot;</span>Umberto Boccioni<span class="String">&quot;</span></span>,
painter: <span class="String"><span class="String">&quot;</span>Vladimir Burliuk<span class="String">&quot;</span></span>,
poet: {
name: <span class="String"><span class="String">&quot;</span>F.T. Marinetti<span class="String">&quot;</span></span>,
address: [<span class="String"><span class="String">&quot;</span>Via Roma 42R<span class="String">&quot;</span></span>, <span class="String"><span class="String">&quot;</span>Bellagio, Italy 22021<span class="String">&quot;</span></span>]
}
};
_ref <span class="Keyword">=</span> futurists.poet, name <span class="Keyword">=</span> _ref.<span class="LibraryConstant">name</span>, _ref2 <span class="Keyword">=</span> _ref.address, street <span class="Keyword">=</span> _ref2[<span class="Number">0</span>], city <span class="Keyword">=</span> _ref2[<span class="Number">1</span>];
</pre><button onclick='javascript: var city, futurists, name, street, _ref, _ref2;
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, _ref2 = _ref.address, street = _ref2[0], city = _ref2[1];;alert(name + " — " + street);'>run: name + " — " + street</button><br class='clear' /></div>
<p>
Pattern matching can even be combined with splats.
</p>
<div class='code'><pre class="idle">tag <span class="Keyword">=</span> <span class="String"><span class="String">&quot;</span>&lt;impossible&gt;<span class="String">&quot;</span></span>
<span class="Keyword">[</span>open, contents..., close<span class="Keyword">] =</span> tag.split(<span class="String"><span class="String">&quot;</span><span class="String">&quot;</span></span>)
</pre><pre class="idle"><span class="Storage">var</span> close, contents, open, tag, _i, _ref;
<span class="Storage">var</span> __slice <span class="Keyword">=</span> <span class="LibraryClassType">Array</span>.<span class="LibraryConstant">prototype</span>.slice;
tag <span class="Keyword">=</span> <span class="String"><span class="String">&quot;</span>&lt;impossible&gt;<span class="String">&quot;</span></span>;
_ref <span class="Keyword">=</span> tag.<span class="LibraryFunction">split</span>(<span class="String"><span class="String">&quot;</span><span class="String">&quot;</span></span>), open <span class="Keyword">=</span> _ref[<span class="Number">0</span>], contents <span class="Keyword">=</span> <span class="Number">3</span> <span class="Keyword">&lt;=</span> _ref.<span class="LibraryConstant">length</span> ? __slice.<span class="LibraryFunction">call</span>(_ref, <span class="Number">1</span>, _i <span class="Keyword">=</span> _ref.<span class="LibraryConstant">length</span> <span class="Keyword">-</span> <span class="Number">1</span>) : (_i <span class="Keyword">=</span> <span class="Number">1</span>, []), close <span class="Keyword">=</span> _ref[_i<span class="Keyword">++</span>];
</pre><button onclick='javascript: var close, contents, open, tag, _i, _ref;
var __slice = Array.prototype.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("")</button><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
as 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 class="idle"><span class="FunctionName">Account </span><span class="Keyword">=</span> <span class="FunctionArgument">(customer, cart)</span> <span class="Storage">-&gt;</span>
<span class="Variable">@customer</span> <span class="Keyword">=</span> customer
<span class="Variable">@cart</span> <span class="Keyword">=</span> cart
$(<span class="String"><span class="String">'</span>.shopping_cart<span class="String">'</span></span>).bind <span class="String"><span class="String">'</span>click<span class="String">'</span></span>, <span class="FunctionArgument">(event)</span> <span class="Storage">=&gt;</span>
<span class="Variable">@customer</span>.purchase <span class="Variable">@cart</span>
</pre><pre class="idle"><span class="Storage">var</span> Account;
<span class="Storage">var</span> <span class="FunctionName">__bind</span> = <span class="Storage">function</span>(<span class="FunctionArgument">fn, me</span>){ <span class="Keyword">return</span> <span class="Storage">function</span>(){ <span class="Keyword">return</span> fn.<span class="LibraryFunction">apply</span>(me, arguments); }; };
<span class="FunctionName">Account</span> = <span class="Storage">function</span>(<span class="FunctionArgument">customer, cart</span>) {
<span class="Variable">this</span>.customer <span class="Keyword">=</span> customer;
<span class="Variable">this</span>.cart <span class="Keyword">=</span> cart;
<span class="Keyword">return</span> <span class="Keyword">$</span>(<span class="String"><span class="String">'</span>.shopping_cart<span class="String">'</span></span>).bind(<span class="String"><span class="String">'</span>click<span class="String">'</span></span>, __bind(<span class="Storage">function</span>(<span class="LibraryClassType">event</span>) {
<span class="Keyword">return</span> <span class="Variable">this</span>.customer.purchase(<span class="Variable">this</span>.cart);
}, <span class="Variable">this</span>));
};
</pre><br class='clear' /></div>
<p>
If we had used <tt>-></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>
<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 class="idle">hi <span class="Keyword">=</span> <span class="String"><span class="String">`</span>function() {</span>
<span class="String"> return [document.title, &quot;Hello JavaScript&quot;].join(&quot;: &quot;);</span>
<span class="String">}<span class="String">`</span></span>
</pre><pre class="idle"><span class="Storage">var</span> hi;
<span class="FunctionName">hi</span> = <span class="Storage">function</span>() {
<span class="Keyword">return</span> [<span class="LibraryClassType">document</span>.<span class="LibraryConstant">title</span>, <span class="String"><span class="String">&quot;</span>Hello JavaScript<span class="String">&quot;</span></span>].<span class="LibraryFunction">join</span>(<span class="String"><span class="String">&quot;</span>: <span class="String">&quot;</span></span>);
};
</pre><button onclick='javascript: var hi;
hi = function() {
return [document.title, "Hello JavaScript"].join(": ");
};;alert(hi());'>run: hi()</button><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 class="idle"><span class="Keyword">switch</span> day
<span class="Keyword">when</span> <span class="String"><span class="String">&quot;</span>Mon<span class="String">&quot;</span></span> <span class="Keyword">then</span> go work
<span class="Keyword">when</span> <span class="String"><span class="String">&quot;</span>Tue<span class="String">&quot;</span></span> <span class="Keyword">then</span> go relax
<span class="Keyword">when</span> <span class="String"><span class="String">&quot;</span>Thu<span class="String">&quot;</span></span> <span class="Keyword">then</span> go iceFishing
<span class="Keyword">when</span> <span class="String"><span class="String">&quot;</span>Fri<span class="String">&quot;</span></span>, <span class="String"><span class="String">&quot;</span>Sat<span class="String">&quot;</span></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"><span class="String">&quot;</span>Sun<span class="String">&quot;</span></span> <span class="Keyword">then</span> go church
<span class="Keyword">else</span> go work
</pre><pre class="idle"><span class="Keyword">switch</span> (day) {
<span class="Keyword">case</span> <span class="String"><span class="String">&quot;</span>Mon<span class="String">&quot;</span></span>:
<span class="LibraryFunction">go</span>(work);
<span class="Keyword">break</span>;
<span class="Keyword">case</span> <span class="String"><span class="String">&quot;</span>Tue<span class="String">&quot;</span></span>:
<span class="LibraryFunction">go</span>(relax);
<span class="Keyword">break</span>;
<span class="Keyword">case</span> <span class="String"><span class="String">&quot;</span>Thu<span class="String">&quot;</span></span>:
<span class="LibraryFunction">go</span>(iceFishing);
<span class="Keyword">break</span>;
<span class="Keyword">case</span> <span class="String"><span class="String">&quot;</span>Fri<span class="String">&quot;</span></span>:
<span class="Keyword">case</span> <span class="String"><span class="String">&quot;</span>Sat<span class="String">&quot;</span></span>:
<span class="Keyword">if</span> (day <span class="Keyword">===</span> bingoDay) {
<span class="LibraryFunction">go</span>(bingo);
<span class="LibraryFunction">go</span>(dancing);
}
<span class="Keyword">break</span>;
<span class="Keyword">case</span> <span class="String"><span class="String">&quot;</span>Sun<span class="String">&quot;</span></span>:
<span class="LibraryFunction">go</span>(church);
<span class="Keyword">break</span>;
<span class="Keyword">default</span>:
<span class="LibraryFunction">go</span>(work);
}
</pre><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 class="idle"><span class="Keyword">try</span>
allHellBreaksLoose()
catsAndDogsLivingTogether()
<span class="Keyword">catch</span> error
print error
<span class="Keyword">finally</span>
cleanUp()
</pre><pre class="idle"><span class="Keyword">try</span> {
allHellBreaksLoose();
catsAndDogsLivingTogether();
} <span class="Keyword">catch</span> (error) {
<span class="LibraryFunction">print</span>(error);
} <span class="Keyword">finally</span> {
cleanUp();
}
</pre><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 class="idle">cholesterol <span class="Keyword">=</span> <span class="Number">127</span>
healthy <span class="Keyword">=</span> <span class="Number">200</span> <span class="Keyword">&gt;</span> cholesterol <span class="Keyword">&gt;</span> <span class="Number">60</span>
</pre><pre class="idle"><span class="Storage">var</span> cholesterol, healthy;
cholesterol <span class="Keyword">=</span> <span class="Number">127</span>;
healthy <span class="Keyword">=</span> <span class="Number">200</span> <span class="Keyword">&gt;</span> cholesterol <span class="Keyword">&amp;</span><span class="Keyword">&amp;</span> cholesterol <span class="Keyword">&gt;</span> <span class="Number">60</span>;
</pre><button onclick='javascript: var cholesterol, healthy;
cholesterol = 127;
healthy = 200 > cholesterol && cholesterol > 60;;alert(healthy);'>run: healthy</button><br class='clear' /></div>
<p>
<span id="strings" class="bookmark"></span>
<b class="header">String Interpolation, Heredocs, 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 class="idle">author <span class="Keyword">=</span> <span class="String"><span class="String">&quot;</span>Wittgenstein<span class="String">&quot;</span></span>
quote <span class="Keyword">=</span> <span class="String"><span class="String">&quot;</span>A picture is a fact. -- <span class="String"><span class="String">#{</span> author <span class="String">}</span></span><span class="String">&quot;</span></span>
sentence <span class="Keyword">=</span> <span class="String"><span class="String">&quot;</span><span class="String"><span class="String">#{</span> <span class="Number">22</span> <span class="Keyword">/</span> <span class="Number">7</span> <span class="String">}</span></span> is a decent approximation of π<span class="String">&quot;</span></span>
</pre><pre class="idle"><span class="Storage">var</span> author, quote, sentence;
author <span class="Keyword">=</span> <span class="String"><span class="String">&quot;</span>Wittgenstein<span class="String">&quot;</span></span>;
quote <span class="Keyword">=</span> <span class="String"><span class="String">&quot;</span>A picture is a fact. -- <span class="String">&quot;</span></span> <span class="Keyword">+</span> author;
sentence <span class="Keyword">=</span> <span class="String"><span class="String">&quot;</span><span class="String">&quot;</span></span> <span class="Keyword">+</span> (<span class="Number">22</span> / <span class="Number">7</span>) <span class="Keyword">+</span> <span class="String"><span class="String">&quot;</span> is a decent approximation of π<span class="String">&quot;</span></span>;
</pre><button 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</button><br class='clear' /></div>
<p>
Multiline strings are allowed in CoffeeScript.
</p>
<div class='code'><pre class="idle">mobyDick <span class="Keyword">=</span> <span class="String"><span class="String">&quot;</span>Call me Ishmael. Some years ago --</span>
<span class="String"> never mind how long precisely -- having little</span>
<span class="String"> or no money in my purse, and nothing particular</span>
<span class="String"> to interest me on shore, I thought I would sail</span>
<span class="String"> about a little and see the watery part of the</span>
<span class="String"> world...<span class="String">&quot;</span></span>
</pre><pre class="idle"><span class="Storage">var</span> mobyDick;
mobyDick <span class="Keyword">=</span> <span class="String"><span class="String">&quot;</span>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 class="String">&quot;</span></span>;
</pre><button 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</button><br class='clear' /></div>
<p>
Heredocs can be used to hold formatted or indentation-sensitive text
(or, if you just don't feel like escaping quotes and apostrophes). The
indentation level that begins the heredoc is maintained throughout, so
you can keep it all aligned with the body of your code.
</p>
<div class='code'><pre class="idle">html <span class="Keyword">=</span> <span class="String"><span class="String">'''</span></span>
<span class="String"> &lt;strong&gt;</span>
<span class="String"> cup of coffeescript</span>
<span class="String"> &lt;/strong&gt;</span>
<span class="String"> <span class="String">'''</span></span>
</pre><pre class="idle"><span class="Storage">var</span> html;
html <span class="Keyword">=</span> <span class="String"><span class="String">'</span>&lt;strong&gt;<span class="UserDefinedConstant">\n</span> cup of coffeescript<span class="UserDefinedConstant">\n</span>&lt;/strong&gt;<span class="String">'</span></span>;
</pre><br class='clear' /></div>
<p>
Double-quoted heredocs, like 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 synax for heredocs,
are preserved in the generated code.
</p>
<div class='code'><pre class="idle"><span class="Comment"><span class="Comment">###</span></span>
<span class="Comment">CoffeeScript Compiler v0.9.5</span>
<span class="Comment">Released under the MIT License</span>
<span class="Comment">###</span>
</pre><pre class="idle"><span class="Comment"><span class="Comment">/*</span></span>
<span class="Comment">CoffeeScript Compiler v0.9.5</span>
<span class="Comment">Released under the MIT License</span>
<span class="Comment"><span class="Comment">*/</span></span>
</pre><br class='clear' /></div>
<p>
<span id="regexes" class="bookmark"></span>
<b class="header">Extended Regular Expressions</b>
Similar to "heredocs" and "herecomments", CoffeeScript supports "heregexes" &mdash;
extended regular expressions that ignore internal whitespace and can contain
comments, after Perl's <tt>/x</tt> modifier, but delimited by <tt>///</tt>.
They go a long way towards making complex regular expressions readable.
To quote from the CoffeeScript source:
</p>
<div class='code'><pre class="idle">OPERATOR <span class="Keyword">=</span> <span class="String">/// ^ (</span>
<span class="String"> ?: [-=]&gt; <span class="Comment"><span class="Comment">#</span> function</span></span>
<span class="String"> | [-+*/%&lt;&gt;&amp;|^!?=]= <span class="Comment"><span class="Comment">#</span> compound assign / compare</span></span>
<span class="String"> | &gt;&gt;&gt;=? <span class="Comment"><span class="Comment">#</span> zero-fill right shift</span></span>
<span class="String"> | ([-+:])\1 <span class="Comment"><span class="Comment">#</span> doubles</span></span>
<span class="String"> | ([&amp;|&lt;&gt;])\2=? <span class="Comment"><span class="Comment">#</span> logic / shift</span></span>
<span class="String"> | \?\. <span class="Comment"><span class="Comment">#</span> soak access</span></span>
<span class="String"> | \.{2,3} <span class="Comment"><span class="Comment">#</span> range or splat</span></span>
<span class="String">) ///</span>
</pre><pre class="idle"><span class="Storage">var</span> OPERATOR;
OPERATOR <span class="Keyword">=</span><span class="String"> <span class="String">/</span>^(?:[-=]&gt;|[-+*<span class="UserDefinedConstant">\/</span>%&lt;&gt;&amp;|^!?=]=|&gt;&gt;&gt;=?|([-+:])<span class="UserDefinedConstant">\1</span>|([&amp;|&lt;&gt;])<span class="UserDefinedConstant">\2</span>=?|<span class="UserDefinedConstant">\?</span><span class="UserDefinedConstant">\.</span>|<span class="UserDefinedConstant">\.</span>{2,3})<span class="String">/</span></span>;
</pre><br class='clear' /></div>
<h2>
<span id="cake" class="bookmark"></span>
Cake, and Cakefiles
</h2>
<p>
CoffeeScript includes a 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 build and test tasks for the CoffeeScript
language itself. Tasks are defined in a file named <tt>Cakefile</tt>, and
can be invoked by running <tt>cake taskname</tt> from within the directory.
To print a list of all the tasks and options, just run <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 class="idle">fs <span class="Keyword">=</span> require <span class="String"><span class="String">'</span>fs<span class="String">'</span></span>
option <span class="String"><span class="String">'</span>-o<span class="String">'</span></span>, <span class="String"><span class="String">'</span>--output [DIR]<span class="String">'</span></span>, <span class="String"><span class="String">'</span>directory for compiled code<span class="String">'</span></span>
task <span class="String"><span class="String">'</span>build:parser<span class="String">'</span></span>, <span class="String"><span class="String">'</span>rebuild the Jison parser<span class="String">'</span></span>, <span class="FunctionArgument">(options)</span> <span class="Storage">-&gt;</span>
require <span class="String"><span class="String">'</span>jison<span class="String">'</span></span>
code <span class="Keyword">=</span> require(<span class="String"><span class="String">'</span>./lib/grammar<span class="String">'</span></span>).parser.generate()
dir <span class="Keyword">=</span> options.output <span class="Keyword">or</span> <span class="String"><span class="String">'</span>lib<span class="String">'</span></span>
fs.writeFile <span class="String"><span class="String">&quot;</span><span class="String"><span class="String">#{</span>dir<span class="String">}</span></span>/parser.js<span class="String">&quot;</span></span>, code
</pre><pre class="idle"><span class="Storage">var</span> fs;
fs <span class="Keyword">=</span> require(<span class="String"><span class="String">'</span>fs<span class="String">'</span></span>);
option(<span class="String"><span class="String">'</span>-o<span class="String">'</span></span>, <span class="String"><span class="String">'</span>--output [DIR]<span class="String">'</span></span>, <span class="String"><span class="String">'</span>directory for compiled code<span class="String">'</span></span>);
task(<span class="String"><span class="String">'</span>build:parser<span class="String">'</span></span>, <span class="String"><span class="String">'</span>rebuild the Jison parser<span class="String">'</span></span>, <span class="Storage">function</span>(options) {
<span class="Storage">var</span> code, dir;
require(<span class="String"><span class="String">'</span>jison<span class="String">'</span></span>);
code <span class="Keyword">=</span> require(<span class="String"><span class="String">'</span>./lib/grammar<span class="String">'</span></span>).parser.generate();
dir <span class="Keyword">=</span> options.output <span class="Keyword">||</span> <span class="String"><span class="String">'</span>lib<span class="String">'</span></span>;
<span class="Keyword">return</span> fs.writeFile(<span class="String"><span class="String">&quot;</span><span class="String">&quot;</span></span> <span class="Keyword">+</span> dir <span class="Keyword">+</span> <span class="String"><span class="String">&quot;</span>/parser.js<span class="String">&quot;</span></span>, code);
});
</pre><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>
</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 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="examples" class="bookmark"></span>
Examples
</h2>
<ul>
<li>
<b>frank06</b>'s <a href="http://riakjs.org/">riak-js</a>, a Node.js client for
<a href="http://www.basho.com/Riak.html">Riak</a>, with support for HTTP
and Protocol Buffers.
</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>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>josh</b>'s <a href="http://josh.github.com/nack/">nack</a>, a Node.js-powered
<a href="http://rack.rubyforge.org/">Rack</a> server.
</li>
<li>
<b>sstephenson</b>'s <a href="http://sstephenson.github.com/strscan-js/">StringScanner</a>,
a simple tokenizer and lexical scanner for JavaScript strings.
</li>
</ul>
<h2>
<span id="resources" class="bookmark"></span>
Resources
</h2>
<ul>
<li>
<a href="http://github.com/jashkenas/coffee-script/">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/coffee-script/issues">CoffeeScript Issues</a><br />
Bugs reports, feature requests, and general discussion all belong here.
</li>
<li>
If you'd like to chat, stop by <tt>#coffeescript</tt> on Freenode in the
IRC client of your choice, or on
<a href="http://webchat.freenode.net/">webchat.freenode.net</a>.
</li>
<li>
<b>satyr</b>'s <a href="http://github.com/satyr/coco">Coco</a>
&mdash; a CoffeeScript dialect that aims to be more radical and practical.
</li>
<li>
<b>yeungda</b>'s <a href="http://github.com/yeungda/jcoffeescript">JCoffeeScript</a>
&mdash; A Java Library that uses Rhino to compile CoffeeScript, allowing
compilation within Java projects or on systems that Node.js doesn't support.
</li>
<li>
<b>defunkt</b>'s <a href="http://github.com/defunkt/coffee-mode">CoffeeScript Major Mode</a>
&mdash; a Emacs major mode that provides syntax highlighting, indentation
support, and some bonus commands.
</li>
<li>
<b>jashkenas</b>' <a href="http://github.com/jashkenas/coffee-script-tmbundle">CoffeeScript TextMate Bundle</a>
&mdash; which provides syntax highlighting, snippet expansion, and the
ability to run bits of CoffeeScript from within TextMate itself.
</li>
<li>
<b>kchmck</b>'s <a href="http://github.com/kchmck/vim-coffee-script">Vim CoffeeScript</a>
&mdash; which adds Vim syntax highlighting and indentation support.
</li>
<li>
<b>wavded</b>'s <a href="http://github.com/wavded/gedit-coffeescript">gedit-coffeescript</a>
&mdash; a CoffeeScript syntax highlighter for the gedit text editor.
</li>
<li>
<b>yeungda</b>'s <a href="http://yeungda.github.com/coffeescript-idea/">coffeescript-idea</a>
&mdash; a plugin for IntelliJ IDEA and RubyMine providing syntax highlighting.
</li>
<li>
<b>mattly</b>'s <a href="http://github.com/mattly/rack-coffee">rack-coffee</a>
&mdash; a small Rack middleware for serving CoffeeScript files as
compiled JavaScript on the fly.
</li>
<li>
<b>jnicklas</b>'s <a href="http://github.com/jnicklas/bistro_car">BistroCar</a>
&mdash; a plugin that serves and bundles CoffeeScript from within your
Rails application.
</li>
<li>
<b>dsc</b>'s <a href="http://github.com/dsc/coffeecup">CoffeeCup</a>
&mdash; a Python WSGI middleware that compiles CoffeeScript to JavaScript
on-demand during development.
</li>
<li>
<b>sutto</b>'s <a href="http://github.com/Sutto/barista">Barista</a>
&mdash; a BistroCar alternative that integrates well with
<a href="http://documentcloud.github.com/jammit">Jammit</a> and Rails 3.
</li>
<li>
<b>inem</b> and <b>gerad</b>'s <a href="http://github.com/gerad/coffee-haml-filter">coffee-haml-filter</a>
&mdash; a custom filter for rendering CoffeeScript inline within
<a href="http://haml-lang.com/">HAML</a> templates.
</li>
<li>
<b>chrislloyd</b>'s <a href="http://github.com/chrislloyd/roast">Roast</a>
&mdash; a CoffeeScript compiler plug-in that allows you to include external
source files.
</li>
<li>
<b>andrzejsliwa</b>'s <a href="http://github.com/andrzejsliwa/coffeeapp">CoffeeApp</a>
&mdash; a CoffeeScript wrapper for CouchApps, web applications served
directly from CouchDB.
</li>
<li>
<b>sstephenson</b>'s <a href="http://github.com/sstephenson/eco">Eco</a>
&mdash; high-performance embedded CoffeeScript templates, after EJS and ERB.
</li>
<li>
<b>mauricemach</b>'s <a href="http://github.com/mauricemach/coffeekup">CoffeeKup</a>
&mdash; Markup as CoffeeScript. After _why's
<a href="http://markaby.github.com/">Markaby</a>.
</li>
<li>
<b>jashkenas</b>' <a href="http://jashkenas.github.com/docco/">Docco</a>
&mdash; a quick-and-dirty literate-programming-style documentation generator
for CoffeeScript. Used to produce the annotated source.
</li>
<li>
<b>naturalethic</b>'s <a href="http://github.com/naturalethic/Congo">Congo</a>
&mdash; an asynchronous MongoDB ORM, for use with Node.js and CoffeeScript.
</li>
<li>
<b>mauricemach</b>'s <a href="https://github.com/mauricemach/zappa">Zappa</a>
&mdash; a DSL for building web apps, built on top of Express and Socket.IO.
</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="change_log" class="bookmark"></span>
Change Log
</h2>
<p>
<b class="header" style="margin-top: 20px;">0.9.5</b>
0.9.5 should be considered the first release candidate for CoffeeScript 1.0.
There have been a large number of internal changes since the previous release,
many contributed from <b>satyr</b>'s <a href="http://github.com/satyr/coco">Coco</a>
dialect of CoffeeScript. Heregexes (extended regexes) were added. Functions
can now have default arguments. Class bodies are now executable code.
Improved syntax errors for invalid CoffeeScript. Object literals
can now take dynamic keys, like this: <tt>{(key): value}</tt>. <tt>undefined</tt> now
works like <tt>null</tt>, and cannot be assigned a new value.
</p>
<p>
<b class="header" style="margin-top: 20px;">0.9.4</b>
CoffeeScript now uses appropriately-named temporary variables, and recycles
their references after use. Added <tt>require.extensions</tt> support for
<b>Node.js 0.3</b>. Loading CoffeeScript in the browser now adds just a
single <tt>CoffeeScript</tt> object to global scope.
Fixes for implicit object and block comment edge cases.
</p>
<p>
<b class="header" style="margin-top: 20px;">0.9.3</b>
CoffeeScript <tt>switch</tt> statements now compile into JS <tt>switch</tt>
statements &mdash; they previously compiled into <tt>if/else</tt> chains
for JavaScript 1.3 compatibility.
Soaking a function invocation is now supported. Users of the RubyMine
editor should now be able to use <tt>--watch</tt> mode.
</p>
<p>
<b class="header" style="margin-top: 20px;">0.9.2</b>
Specifying the start and end of a range literal is now optional, eg. <tt>array[3..]</tt>.
You can now say <tt>a not instanceof b</tt>.
Fixed important bugs with nested significant and non-significant indentation (Issue #637).
Added a <tt>--require</tt> flag that allows you to hook into the <tt>coffee</tt> command.
Added a custom <tt>jsl.conf</tt> file for our preferred JavaScriptLint setup.
Sped up Jison grammar compilation time by flattening rules for operations.
Block comments can now be used with JavaScript-minifier-friendly syntax.
Added JavaScript's compound assignment bitwise operators. Bugfixes to
implicit object literals with leading number and string keys, as the subject
of implicit calls, and as part of compound assignment.
</p>
<p>
<b class="header" style="margin-top: 20px;">0.9.1</b>
Bugfix release for <b>0.9.1</b>. Greatly improves the handling of mixed
implicit objects, implicit function calls, and implicit indentation.
String and regex interpolation is now strictly <tt>#{ ... }</tt> (Ruby style).
The compiler now takes a <tt>--require</tt> flag, which specifies scripts
to run before compilation.
</p>
<p>
<b class="header" style="margin-top: 20px;">0.9.0</b>
The CoffeeScript <b>0.9</b> series is considered to be a release candidate
for <b>1.0</b>; let's give her a shakedown cruise. <b>0.9.0</b> introduces a massive
backwards-incompatible change: Assignment now uses <tt>=</tt>, and object
literals use <tt>:</tt>, as in JavaScript. This allows us to have implicit
object literals, and YAML-style object definitions. Half assignments are
removed, in favor of <tt>+=</tt>, <tt>or=</tt>, and friends.
Interpolation now uses a hash mark <tt>#</tt> instead of the dollar sign
<tt>$</tt> &mdash; because dollar signs may be part of a valid JS identifier.
Downwards range comprehensions are now safe again, and are optimized to
straight for loops when created with integer endpoints.
A fast, unguarded form of object comprehension was added:
<tt>for all key, value of object</tt>. Mentioning the <tt>super</tt> keyword
with no arguments now forwards all arguments passed to the function,
as in Ruby. If you extend class <tt>B</tt> from parent class <tt>A</tt>, if
<tt>A</tt> has an <tt>extended</tt> method defined, it will be called, passing in <tt>B</tt> &mdash;
this enables static inheritance, among other things. Cleaner output for
functions bound with the fat arrow. <tt>@variables</tt> can now be used
in parameter lists, with the parameter being automatically set as a property
on the object &mdash; useful in constructors and setter functions.
Constructor functions can now take splats.
</p>
<p>
<b class="header" style="margin-top: 20px;">0.7.2</b>
Quick bugfix (right after 0.7.1) for a problem that prevented <tt>coffee</tt>
command-line options from being parsed in some circumstances.
</p>
<p>
<b class="header" style="margin-top: 20px;">0.7.1</b>
Block-style comments are now passed through and printed as JavaScript block
comments -- making them useful for licenses and copyright headers. Better
support for running coffee scripts standalone via hashbangs.
Improved syntax errors for tokens that are not in the grammar.
</p>
<p>
<b class="header" style="margin-top: 20px;">0.7.0</b>
Official CoffeeScript variable style is now camelCase, as in JavaScript.
Reserved words are now allowed as object keys, and will be quoted for you.
Range comprehensions now generate cleaner code, but you have to specify <tt>by -1</tt>
if you'd like to iterate downward. Reporting of syntax errors is greatly
improved from the previous release. Running <tt>coffee</tt> with no arguments
now launches the REPL, with Readline support. The <tt>&lt;-</tt> bind operator
has been removed from CoffeeScript. The <tt>loop</tt> keyword was added,
which is equivalent to a <tt>while true</tt> loop. Comprehensions that contain
closures will now close over their variables, like the semantics of a <tt>forEach</tt>.
You can now use bound function in class definitions (bound to the instance).
For consistency, <tt>a in b</tt> is now an array presence check, and <tt>a of b</tt>
is an object-key check. Comments are no longer passed through to the generated
JavaScript.
</p>
<p>
<b class="header" style="margin-top: 20px;">0.6.2</b>
The <tt>coffee</tt> command will now preserve directory structure when
compiling a directory full of scripts. Fixed two omissions that were preventing
the CoffeeScript compiler from running live within Internet Explorer.
There's now a syntax for block comments, similar in spirit to CoffeeScript's heredocs.
ECMA Harmony DRY-style pattern matching is now supported, where the name
of the property is the same as the name of the value: <tt>{name, length}: func</tt>.
Pattern matching is now allowed within comprehension variables. <tt>unless</tt>
is now allowed in block form. <tt>until</tt> loops were added, as the inverse
of <tt>while</tt> loops. <tt>switch</tt> statements are now allowed without
switch object clauses. Compatible
with Node.js <b>v0.1.95</b>.
</p>
<p>
<b class="header" style="margin-top: 20px;">0.6.1</b>
Upgraded CoffeeScript for compatibility with the new Node.js <b>v0.1.90</b>
series.
</p>
<p>
<b class="header" style="margin-top: 20px;">0.6.0</b>
Trailing commas are now allowed, a-la Python. Static
properties may be assigned directly within class definitions,
using <tt>@property</tt> notation.
</p>
<p>
<b class="header" style="margin-top: 20px;">0.5.6</b>
Interpolation can now be used within regular expressions and heredocs, as well as
strings. Added the <tt>&lt;-</tt> bind operator.
Allowing assignment to half-expressions instead of special <tt>||=</tt>-style
operators. The arguments object is no longer automatically converted into
an array. After requiring <tt>coffee-script</tt>, Node.js can now directly
load <tt>.coffee</tt> files, thanks to <b>registerExtension</b>. Multiple
splats can now be used in function calls, arrays, and pattern matching.
</p>
<p>
<b class="header" style="margin-top: 20px;">0.5.5</b>
String interpolation, contributed by
<a href="http://github.com/StanAngeloff">Stan Angeloff</a>.
Since <tt>--run</tt> has been the default since <b>0.5.3</b>, updating
<tt>--stdio</tt> and <tt>--eval</tt> to run by default, pass <tt>--compile</tt>
as well if you'd like to print the result.
</p>
<p>
<b class="header" style="margin-top: 20px;">0.5.4</b>
Bugfix that corrects the Node.js global constants <tt>__filename</tt> and
<tt>__dirname</tt>. Tweaks for more flexible parsing of nested function
literals and improperly-indented comments. Updates for the latest Node.js API.
</p>
<p>
<b class="header" style="margin-top: 20px;">0.5.3</b>
CoffeeScript now has a syntax for defining classes. Many of the core
components (Nodes, Lexer, Rewriter, Scope, Optparse) are using them.
Cakefiles can use <tt>optparse.coffee</tt> to define options for tasks.
<tt>--run</tt> is now the default flag for the <tt>coffee</tt> command,
use <tt>--compile</tt> to save JavaScripts. Bugfix for an ambiguity between
RegExp literals and chained divisions.
</p>
<p>
<b class="header" style="margin-top: 20px;">0.5.2</b>
Added a compressed version of the compiler for inclusion in web pages as
<br /><tt>extras/coffee-script.js</tt>. It'll automatically run any script tags
with type <tt>text/coffeescript</tt> for you. Added a <tt>--stdio</tt> option
to the <tt>coffee</tt> command, for piped-in compiles.
</p>
<p>
<b class="header" style="margin-top: 20px;">0.5.1</b>
Improvements to null soaking with the existential operator, including
soaks on indexed properties. Added conditions to <tt>while</tt> loops,
so you can use them as filters with <tt>when</tt>, in the same manner as
comprehensions.
</p>
<p>
<b class="header" style="margin-top: 20px;">0.5.0</b>
CoffeeScript 0.5.0 is a major release, While there are no language changes,
the Ruby compiler has been removed in favor of a self-hosting
compiler written in pure CoffeeScript.
</p>
<p>
<b class="header" style="margin-top: 20px;">0.3.2</b>
<tt>@property</tt> is now a shorthand for <tt>this.property</tt>.<br />
Switched the default JavaScript engine from Narwhal to Node.js. Pass
the <tt>--narwhal</tt> flag if you'd like to continue using it.
</p>
<p>
<b class="header" style="margin-top: 20px;">0.3.0</b>
CoffeeScript 0.3 includes major syntax changes:
<br />
The function symbol was changed to
<tt>-></tt>, and the bound function symbol is now <tt>=></tt>.
<br />
Parameter lists in function definitions must now be wrapped in parentheses.
<br />
Added property soaking, with the <tt>?.</tt> operator.
<br />
Made parentheses optional, when invoking functions with arguments.
<br />
Removed the obsolete block literal syntax.
</p>
<p>
<b class="header" style="margin-top: 20px;">0.2.6</b>
Added Python-style chained comparisons, the conditional existence
operator <tt>?=</tt>, and some examples from <i>Beautiful Code</i>.
Bugfixes relating to statement-to-expression conversion, arguments-to-array
conversion, and the TextMate syntax highlighter.
</p>
<p>
<b class="header" style="margin-top: 20px;">0.2.5</b>
The conditions in switch statements can now take multiple values at once &mdash;
If any of them are true, the case will run. Added the long arrow <tt>==></tt>,
which defines and immediately binds a function to <tt>this</tt>. While loops can
now be used as expressions, in the same way that comprehensions can. Splats
can be used within pattern matches to soak up the rest of an array.
</p>
<p>
<b class="header" style="margin-top: 20px;">0.2.4</b>
Added ECMAScript Harmony style destructuring assignment, for dealing with
extracting values from nested arrays and objects. Added indentation-sensitive
heredocs for nicely formatted strings or chunks of code.
</p>
<p>
<b class="header" style="margin-top: 20px;">0.2.3</b>
Axed the unsatisfactory <tt>ino</tt> keyword, replacing it with <tt>of</tt> for
object comprehensions. They now look like: <tt>for prop, value of object</tt>.
</p>
<p>
<b class="header" style="margin-top: 20px;">0.2.2</b>
When performing a comprehension over an object, use <tt>ino</tt>, instead
of <tt>in</tt>, which helps us generate smaller, more efficient code at
compile time.
<br />
Added <tt>::</tt> as a shorthand for saying <tt>.prototype.</tt>
<br />
The "splat" symbol has been changed from a prefix asterisk <tt>*</tt>, to
a postfix ellipsis <tt>...</tt>
<br />
Added JavaScript's <tt>in</tt> operator,
empty <tt>return</tt> statements, and empty <tt>while</tt> loops.
<br />
Constructor functions that start with capital letters now include a
safety check to make sure that the new instance of the object is returned.
<br />
The <tt>extends</tt> keyword now functions identically to <tt>goog.inherits</tt>
in Google's Closure Library.
</p>
<p>
<b class="header" style="margin-top: 20px;">0.2.1</b>
Arguments objects are now converted into real arrays when referenced.
</p>
<p>
<b class="header" style="margin-top: 20px;">0.2.0</b>
Major release. Significant whitespace. Better statement-to-expression
conversion. Splats. Splice literals. Object comprehensions. Blocks.
The existential operator. Many thanks to all the folks who posted issues,
with special thanks to
<a href="http://github.com/liamoc">Liam O'Connor-Davis</a> for whitespace
and expression help.
</p>
<p>
<b class="header" style="margin-top: 20px;">0.1.6</b>
Bugfix for running <tt>coffee --interactive</tt> and <tt>--run</tt>
from outside of the CoffeeScript directory. Bugfix for nested
function/if-statements.
</p>
<p>
<b class="header" style="margin-top: 20px;">0.1.5</b>
Array slice literals and array comprehensions can now both take Ruby-style
ranges to specify the start and end. JavaScript variable declaration is
now pushed up to the top of the scope, making all assignment statements into
expressions. You can use <tt>\</tt> to escape newlines.
The <tt>coffee-script</tt> command is now called <tt>coffee</tt>.
</p>
<p>
<b class="header" style="margin-top: 20px;">0.1.4</b>
The official CoffeeScript extension is now <tt>.coffee</tt> instead of
<tt>.cs</tt>, which properly belongs to
<a href="http://en.wikipedia.org/wiki/C_Sharp_(programming_language)">C#</a>.
Due to popular demand, you can now also use <tt>=</tt> to assign. Unlike
JavaScript, <tt>=</tt> can also be used within object literals, interchangeably
with <tt>:</tt>. Made a grammatical fix for chained function calls
like <tt>func(1)(2)(3)(4)</tt>. Inheritance and super no longer use
<tt>__proto__</tt>, so they should be IE-compatible now.
</p>
<p>
<b class="header" style="margin-top: 20px;">0.1.3</b>
The <tt>coffee</tt> command now includes <tt>--interactive</tt>,
which launches an interactive CoffeeScript session, and <tt>--run</tt>,
which directly compiles and executes a script. Both options depend on a
working installation of Narwhal.
The <tt>aint</tt> keyword has been replaced by <tt>isnt</tt>, which goes
together a little smoother with <tt>is</tt>.
Quoted strings are now allowed as identifiers within object literals: eg.
<tt>{"5+5": 10}</tt>.
All assignment operators now use a colon: <tt>+:</tt>, <tt>-:</tt>,
<tt>*:</tt>, etc.
</p>
<p>
<b class="header" style="margin-top: 20px;">0.1.2</b>
Fixed a bug with calling <tt>super()</tt> through more than one level of
inheritance, with the re-addition of the <tt>extends</tt> keyword.
Added experimental <a href="http://narwhaljs.org/">Narwhal</a>
support (as a Tusk package), contributed by
<a href="http://tlrobinson.net/">Tom Robinson</a>, including
<b>bin/cs</b> as a CoffeeScript REPL and interpreter.
New <tt>--no-wrap</tt> option to suppress the safety function
wrapper.
</p>
<p>
<b class="header" style="margin-top: 20px;">0.1.1</b>
Added <tt>instanceof</tt> and <tt>typeof</tt> as operators.
</p>
<p>
<b class="header" style="margin-top: 20px;">0.1.0</b>
Initial CoffeeScript release.
</p>
</div>
<script type="text/coffeescript">
# Set up the compilation function, to run when you stop typing.
compile_source = ->
source = $('#repl_source').val()
window.compiled_js = ''
try
window.compiled_js = CoffeeScript.compile source, bare: on
$('#repl_results').text window.compiled_js
$('#error').hide()
catch error
$('#error').text(error.message).show()
# Listen for keypresses and recompile.
$('#repl_source').keyup -> compile_source()
# Eval the compiled js.
$('button.run').click ->
try
eval window.compiled_js
catch error then alert error
current_nav = null
# Helper to hide the menus.
close_menus = ->
if current_nav
current_nav.removeClass 'active'
document.body.className = 'minimized'
current_nav = null
# Bind navigation buttons to open the menus.
$('.navigation').click (e) ->
return if e.target.tagName.toLowerCase() is 'a'
if this isnt (current_nav and current_nav[0])
close_menus()
current_nav = $(this)
current_nav.addClass 'active'
false
$(document.body).click -> close_menus()
$('.navigation .full_screen').click ->
document.body.className = 'full_screen'
$('.navigation .minimize').click ->
document.body.className = 'minimized'
$('#open_webchat').click ->
$(this).replaceWith $('<iframe src="http://webchat.freenode.net/?channels=coffeescript" width="625" height="400"></iframe>')
compile_source()
</script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script src="extras/coffee-script.js"></script>
</body>
</html>