Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Fetching contributors…

Cannot retrieve contributors at this time

3603 lines (3087 sloc) 182.11 kb
<!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" />
<script>
var __slice = Array.prototype.slice;
window.tame = {
Deferrals: (function() {
function _Class(_arg) {
this.continuation = _arg;
this.count = 1;
this.ret = null;
}
_Class.prototype._fulfill = function() {
if (!--this.count) return this.continuation(this.ret);
};
_Class.prototype.defer = function(defer_params) {
var _this = this;
++this.count;
return function() {
var inner_params, _ref;
inner_params = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
if (defer_params != null) {
if ((_ref = defer_params.assign_fn) != null) {
_ref.apply(null, inner_params);
}
}
return _this._fulfill();
};
};
return _Class;
})()
}
window.__tame_k = function() {};
</script>
</head>
<body>
<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 menu">
<a href="#overview">Overview</a>
<a href="#installation">Installation</a>
<a href="#usage">Usage</a>
<a href="#language">Language Reference</a>
<a href="#tame">Tame Basic Features</a>
<a href="#tame_defer">Tame Defer Values</a>
<a href="#tame_expr">Tame Expressions</a>
<a href="#literals">Literals: Functions, Objects and Arrays</a>
<a href="#lexical_scope">Lexical Scoping and Variable Safety</a>
<a href="#conditionals">If, Else, Unless, and Conditional Assignment</a>
<a href="#splats">Splats...</a>
<a href="#loops">Loops and Comprehensions</a>
<a href="#slices">Array Slicing and Splicing</a>
<a href="#expressions">Everything is an Expression</a>
<a href="#operators">Operators and Aliases</a>
<a href="#classes">Classes, Inheritance, and Super</a>
<a href="#destructuring">Destructuring Assignment</a>
<a href="#fat_arrow">Function Binding</a>
<a href="#embedded">Embedded JavaScript</a>
<a href="#switch">Switch and Try/Catch</a>
<a href="#comparisons">Chained Comparisons</a>
<a href="#strings">String Interpolation, 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="#resources">Books, Screencasts, Examples and Resources</a>
<a href="#changelog">Change Log</a>
</div>
</div>
<div class="navigation try">
<div class="button">
Try CoffeeScript
<div class="repl_bridge"></div>
</div>
<div class="contents repl_wrapper">
<div class="code">
<div class="screenshadow tl"></div>
<div class="screenshadow tr"></div>
<div class="screenshadow bl"></div>
<div class="screenshadow br"></div>
<div id="repl_source_wrap">
<textarea id="repl_source" rows="100" spellcheck="false">alert "Hello CoffeeScript!"</textarea>
</div>
<div id="repl_results_wrap"><pre id="repl_results"></pre></div>
<div class="minibutton dark run" title="Ctrl-Enter">Run</div>
<a class="minibutton permalink" id="repl_permalink">Link</a>
<br class="clear" />
</div>
</div>
</div>
<div class="navigation annotated">
<div class="button">
Annotated Source
</div>
<div class="contents menu">
<a href="documentation/docs/grammar.html">Grammar Rules &mdash; src/grammar</a>
<a href="documentation/docs/lexer.html">Lexing Tokens &mdash; src/lexer</a>
<a href="documentation/docs/rewriter.html">The Rewriter &mdash; src/rewriter</a>
<a href="documentation/docs/nodes.html">The Syntax Tree &mdash; src/nodes</a>
<a href="documentation/docs/scope.html">Lexical Scope &mdash; src/scope</a>
<a href="documentation/docs/helpers.html">Helpers &amp; Utility Functions &mdash; src/helpers</a>
<a href="documentation/docs/coffee-script.html">The CoffeeScript Module &mdash; src/coffee-script</a>
<a href="documentation/docs/cake.html">Cake &amp; Cakefiles &mdash; src/cake</a>
<a href="documentation/docs/command.html">"coffee" Command-Line Utility &mdash; src/command</a>
<a href="documentation/docs/optparse.html">Option Parsing &mdash; src/optparse</a>
<a href="documentation/docs/repl.html">Interactive REPL &mdash; src/repl</a>
</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.
</p>
<p>
But mind you, this is a <b>fork</b> of CoffeeScript,
called <i>AdvancedCoffeeSubstitute (ACS)</i>.
<b>ACS is a drop-in replacement for CoffeeScript
designed to simplify and parallelize asynchronous control flow, both on the
browser, and in the server.</b>
</p>
<p>
The golden rule of CoffeeScript was: <i>"It's just JavaScript"</i>. ACS
is doing something deeper. It's selectively running code through a
<i>continuation-passing style conversion</i>. Original-style
CoffeeScript will compile as before, but code using the new ACS
features will be less recognizable. Still, the compiled output
is readable and pretty-printed, passes through
<a href="http://www.javascriptlint.com/">JavaScript Lint</a>
without warnings, will work in every JavaScript implementation, and tends
to run as fast or faster than the equivalent handwritten JavaScript.
</p>
<p>
<b>Latest Version:</b>
<a href="http://github.com/maxtaco/coffee-script/tarball/1.2.0">1.2.0</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"># Assignment:
number = 42
opposite = true
# Conditions:
number = -42 if opposite
# Functions:
square = (x) -&gt; x * x
# Arrays:
list = [1, 2, 3, 4, 5]
# Objects:
math =
root: Math.sqrt
square: square
cube: (x) -&gt; x * square x
# Splats:
race = (winner, runners...) -&gt;
print winner, runners
# Existence:
alert &quot;I knew it!&quot; if elvis?
# Array comprehensions:
cubes = (math.cube num for num in list)
</pre><pre class="idle"><span class="Storage">var</span> cubes, list, math, num, number, opposite, race, square,
__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>() {
<span class="Storage">var</span> _i, _len, _results;
_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><script>window.example1 = "# Assignment:\nnumber = 42\nopposite = true\n\n# Conditions:\nnumber = -42 if opposite\n\n# Functions:\nsquare = (x) -> x * x\n\n# Arrays:\nlist = [1, 2, 3, 4, 5]\n\n# Objects:\nmath =\n root: Math.sqrt\n square: square\n cube: (x) -> x * square x\n\n# Splats:\nrace = (winner, runners...) ->\n print winner, runners\n\n# Existence:\nalert \"I knew it!\" if elvis?\n\n# Array comprehensions:\ncubes = (math.cube num for num in list)\n\nalert cubes"</script><div class='minibutton ok' onclick='javascript: var cubes, list, math, num, number, opposite, race, square,
__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() {
var _i, _len, _results;
_results = [];
for (_i = 0, _len = list.length; _i < _len; _i++) {
num = list[_i];
_results.push(math.cube(num));
}
return _results;
})();
;alert(cubes);'>run: cubes</div><br class='clear' /></div>
<h2>
<span id="installation" class="bookmark"></span>
Installation
</h2>
<p>
The CoffeeScript compiler is itself
<a href="documentation/docs/grammar.html">written in CoffeeScript</a>,
using the <a href="http://jison.org">Jison parser generator</a>. The
command-line version of <tt>coffee</tt> is available as a
<a href="http://nodejs.org/">Node.js</a> utility. The
<a href="extras/coffee-script.js">core compiler</a> however, does not
depend on Node, and can be run in any JavaScript environment, or in the
browser (see "Try CoffeeScript", above).
</p>
<p>
To install, first make sure you have a working copy of the latest stable version of
<a href="http://nodejs.org/">Node.js</a>, and <a href="http://npmjs.org">npm</a>
(the Node Package Manager). You can then install CoffeeScript with npm:
</p>
<pre>
npm install -g coffee-script</pre>
<p>
(Leave off the <tt>-g</tt> if you don't wish to install globally.)
</p>
<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>
If installing on Ubuntu or Debian,
<a href="http://opinionatedprogrammer.com/2010/12/installing-coffeescript-on-debian-or-ubuntu/">be
careful not to use the existing out-of-date package</a>.
</p>
<h2>
<span id="usage" class="bookmark"></span>
Usage
</h2>
<p>
Once installed, you should have access to the <tt>coffee</tt> command,
which can execute scripts, compile <tt>.coffee</tt> files into <tt>.js</tt>,
and provide an interactive REPL. The <tt>coffee</tt> command takes the
following options:
</p>
<table>
<tr>
<td><code>-c, --compile</code></td>
<td>
Compile a <tt>.coffee</tt> script into a <tt>.js</tt> JavaScript file
of the same name.
</td>
</tr>
<tr>
<td width="25%"><code>-i, --interactive</code></td>
<td>
Launch an interactive CoffeeScript session to try short snippets.
Identical to calling <tt>coffee</tt> with no arguments.
</td>
</tr>
<tr>
<td><code>-o, --output [DIR]</code></td>
<td>
Write out all compiled JavaScript files into the specified directory.
Use in conjunction with <tt>--compile</tt> or <tt>--watch</tt>.
</td>
</tr>
<tr>
<td><code>-j, --join [FILE]</code></td>
<td>
Before compiling, concatenate all scripts together in the order they
were passed, and write them into the specified file.
Useful for building large projects.
</td>
</tr>
<tr>
<td><code>-w, --watch</code></td>
<td>
Watch files for changes, rerunning the specified command when any
file is updated.
</td>
</tr>
<tr>
<td><code>-p, --print</code></td>
<td>
Instead of writing out the JavaScript as a file, print it
directly to <b>stdout</b>.
</td>
</tr>
<tr>
<td><code>-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 "console.log 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
<a href="#lexical_scope">top-level function safety wrapper</a>.
</td>
</tr>
<tr>
<td><code>-t, --tokens</code></td>
<td>
Instead of parsing the CoffeeScript, just lex it, and print out the
token stream: <tt>[IDENTIFIER square] [ASSIGN =] [PARAM_START (]</tt> ...
</td>
</tr>
<tr>
<td><code>-n, --nodes</code></td>
<td>
Instead of compiling the CoffeeScript, just lex and parse it, and print
out the parse tree:
<pre class="no_bar">
Expressions
Assign
Value "square"
Code "x"
Op *
Value "x"
Value "x"</pre>
</td>
</tr>
<tr>
<td><code>--nodejs</code></td>
<td>
The <tt>node</tt> executable has some useful options you can set,
such as<br /> <tt>--debug</tt>, <tt>--debug-brk</tt> and <tt>--max-stack-size</tt>. Use this
flag to forward options directly to Node.js.
</td>
</tr>
</table>
<p>
<b>Examples:</b>
</p>
<ul>
<li>
Compile a directory tree of <tt>.coffee</tt> files in <tt>src</tt> into a parallel
tree of <tt>.js</tt> files in <tt>lib</tt>:<br />
<tt>coffee --compile --output lib/ src/</tt>
</li>
<li>
Watch a file for changes, and recompile it every time the file is saved:<br />
<tt>coffee --watch --compile experimental.coffee</tt>
</li>
<li>
Concatenate a list of files into a single script:<br />
<tt>coffee --join project.js --compile src/*.coffee</tt>
</li>
<li>
Print out the compiled JS from a one-liner:<br />
<tt>coffee -bpe "alert i for i in [0..10]"</tt>
</li>
<li>
All together now, watch and recompile an entire project as you work on it:<br />
<tt>coffee -o lib/ -cw src/</tt>
</li>
<li>
Start the CoffeeScript REPL:<br />
<tt>coffee</tt>
</li>
</ul>
<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. <b>Early sections focus on new/forked ACS features</b>.
Later sections use ideas and syntax previously introduced.
Familiarity with JavaScript is assumed.
In all of the following examples, the source CoffeeScript is provided on
the left, and the direct compilation into JavaScript is on the right.
</i>
</p>
<p>
<i>
Many of the examples can be run (where it makes sense) by pressing the <b>run</b>
button on the right, and can be loaded into the "Try CoffeeScript"
console by pressing the <b>load</b> button on the left.
</i>
<p>
First, the basics: CoffeeScript uses significant whitespace to delimit blocks of code.
You don't need to use semicolons <tt>;</tt> to terminate expressions,
ending the line will do just as well (although semicolons can still
be used to fit multiple expressions onto a single line).
Instead of using curly braces
<tt>{ }</tt> to surround blocks of code in <a href="#literals">functions</a>,
<a href="#conditionals">if-statements</a>,
<a href="#switch">switch</a>, and <a href="#try">try/catch</a>,
use indentation.
</p>
<p>
You don't need to use parentheses to invoke a function if you're passing
arguments. The implicit call wraps forward to the end of the line or block expression.<br />
<tt>console.log sys.inspect object</tt> &rarr; <tt>console.log(sys.inspect(object));</tt>
</p>
<p>
<span id ="tame" class = "bookmark"></span>
<b class="header">Tame Basics</b>
Here is simple example that waits for 1 second, and then calls <tt>alert</tt>:
</p>
<p>
<div class='code'><pre class="idle">await setTimeout defer(), 1000
alert &quot;back after a 1s delay&quot;
</pre><pre class="idle"><span class="Storage">var</span> __tame_deferrals, __tame_k,
_this <span class="Keyword">=</span> <span class="Variable">this</span>;
<span class="FunctionName">__tame_k</span> = <span class="Storage">function</span>() {};
(<span class="Storage">function</span>(__tame_k) {
__tame_deferrals <span class="Keyword">=</span> <span class="Keyword">new</span> <span class="TypeName">tame.Deferrals</span>(__tame_k);
<span class="LibraryFunction">setTimeout</span>(__tame_deferrals.<span class="LibraryConstant">defer</span>({}), <span class="Number">1000</span>);
__tame_deferrals._fulfill();
})(<span class="Storage">function</span>() {
<span class="Keyword">return</span> <span class="LibraryFunction">alert</span>(<span class="String"><span class="String">&quot;</span>back after a 1s delay<span class="String">&quot;</span></span>);
});
</pre><script>window.example2 = "await setTimeout defer(), 1000\nalert \"back after a 1s delay\"\n"</script><div class='minibutton load' onclick='javascript: loadConsole(example2);'>load</div><div class='minibutton ok' onclick='javascript: var __tame_deferrals, __tame_k,
_this = this;
__tame_k = function() {};
(function(__tame_k) {
__tame_deferrals = new tame.Deferrals(__tame_k);
setTimeout(__tame_deferrals.defer({}), 1000);
__tame_deferrals._fulfill();
})(function() {
return alert("back after a 1s delay");
});
;'>run</div><br class='clear' /></div>
</p>
<p>
There is one new language addition here, the <tt>await { ... }</tt> block,
and also one new primitive
function, <tt>defer</tt>. The two of them work in concert. A
function must "wait" at the close of an await block until all
deferrals made in that await block are fulfilled. The
function <tt>defer</tt> returns a callback, and a callee in an
await block can fulfill a deferral by simply calling the callback
it was given. In the code above, there is only one deferral
produced, so after it's fulfilled by `setTimer` in 1000ms, control
continues past the `await` block, onto the alert. The code looks
and feels like threaded code, but is still in the asynchronous
idiom (if you look at the rewritten code output by
the <tt>coffee</tt> compiler).
</p>
<p>
The next example shows some of the power of the tame primitives.
In the following examples, there are two operations that fire in
parallel, and a third that fires after the first two complete:
</p>
<p>
<div class='code'><pre class="idle">window.slowAlert = (w,s,cb) -&gt;
await setTimeout defer(), w
alert s
cb()
await
slowAlert 500, &quot;hello&quot;, defer()
slowAlert 1000, &quot;friend&quot;, defer()
await slowAlert 500, &quot;back after a delay&quot;, defer()
</pre><pre class="idle"><span class="Storage">var</span> __tame_deferrals, __tame_k,
_this <span class="Keyword">=</span> <span class="Variable">this</span>;
<span class="FunctionName">__tame_k</span> = <span class="Storage">function</span>() {};
<span class="LibraryClassType">window</span>.<span class="FunctionName">slowAlert</span> = <span class="Storage">function</span>(<span class="FunctionArgument">w, s, cb</span>) {
<span class="Storage">var</span> __tame_deferrals,
_this <span class="Keyword">=</span> <span class="Variable">this</span>;
(<span class="Storage">function</span>(__tame_k) {
__tame_deferrals <span class="Keyword">=</span> <span class="Keyword">new</span> <span class="TypeName">tame.Deferrals</span>(__tame_k);
<span class="LibraryFunction">setTimeout</span>(__tame_deferrals.<span class="LibraryConstant">defer</span>({}), w);
__tame_deferrals._fulfill();
})(<span class="Storage">function</span>() {
<span class="LibraryFunction">alert</span>(s);
<span class="Keyword">return</span> cb();
});
};
(<span class="Storage">function</span>(__tame_k) {
__tame_deferrals <span class="Keyword">=</span> <span class="Keyword">new</span> <span class="TypeName">tame.Deferrals</span>(__tame_k);
slowAlert(<span class="Number">500</span>, <span class="String"><span class="String">&quot;</span>hello<span class="String">&quot;</span></span>, __tame_deferrals.<span class="LibraryConstant">defer</span>({}));
slowAlert(<span class="Number">1000</span>, <span class="String"><span class="String">&quot;</span>friend<span class="String">&quot;</span></span>, __tame_deferrals.<span class="LibraryConstant">defer</span>({}));
__tame_deferrals._fulfill();
})(<span class="Storage">function</span>() {
__tame_deferrals <span class="Keyword">=</span> <span class="Keyword">new</span> <span class="TypeName">tame.Deferrals</span>(__tame_k);
slowAlert(<span class="Number">500</span>, <span class="String"><span class="String">&quot;</span>back after a delay<span class="String">&quot;</span></span>, __tame_deferrals.<span class="LibraryConstant">defer</span>({}));
__tame_deferrals._fulfill();
});
</pre><script>window.example3 = "window.slowAlert = (w,s,cb) ->\n await setTimeout defer(), w\n alert s\n cb()\nawait\n slowAlert 500, \"hello\", defer()\n slowAlert 1000, \"friend\", defer()\nawait slowAlert 500, \"back after a delay\", defer()\n"</script><div class='minibutton load' onclick='javascript: loadConsole(example3);'>load</div><div class='minibutton ok' onclick='javascript: var __tame_deferrals, __tame_k,
_this = this;
__tame_k = function() {};
window.slowAlert = function(w, s, cb) {
var __tame_deferrals,
_this = this;
(function(__tame_k) {
__tame_deferrals = new tame.Deferrals(__tame_k);
setTimeout(__tame_deferrals.defer({}), w);
__tame_deferrals._fulfill();
})(function() {
alert(s);
return cb();
});
};
(function(__tame_k) {
__tame_deferrals = new tame.Deferrals(__tame_k);
slowAlert(500, "hello", __tame_deferrals.defer({}));
slowAlert(1000, "friend", __tame_deferrals.defer({}));
__tame_deferrals._fulfill();
})(function() {
__tame_deferrals = new tame.Deferrals(__tame_k);
slowAlert(500, "back after a delay", __tame_deferrals.defer({}));
__tame_deferrals._fulfill();
});
;'>run</div><br class='clear' /></div>
</p>
<p>
As one might expect, the tame constructs interoperate with standard
coffee control structures. The following program will call
<tt>slowAlert</tt> three times sequentially:
</p>
<p>
<div class='code'><pre class="idle">for i in [0..3]
await slowAlert 200, &quot;loop iteration #{i}&quot;, defer()
</pre><pre class="idle"><span class="Storage">var</span> i, __tame_deferrals, _i, _next, _while,
_this <span class="Keyword">=</span> <span class="Variable">this</span>;
<span class="FunctionName">__tame_k</span> = <span class="Storage">function</span>() {};
i <span class="Keyword">=</span> <span class="Number">0</span>;
<span class="FunctionName">_while</span> = <span class="Storage">function</span>(<span class="FunctionArgument">__tame_k</span>) {
<span class="Storage">var</span> _break, _continue;
_break <span class="Keyword">=</span> __tame_k;
<span class="FunctionName">_continue</span> = <span class="Storage">function</span>() {
<span class="Keyword">++</span>i;
<span class="Keyword">return</span> _while(__tame_k);
};
_next <span class="Keyword">=</span> _continue;
<span class="Keyword">if</span> (i <span class="Keyword">&lt;=</span> <span class="Number">3</span>) {
(<span class="Storage">function</span>(__tame_k) {
__tame_deferrals <span class="Keyword">=</span> <span class="Keyword">new</span> <span class="TypeName">tame.Deferrals</span>(__tame_k);
slowAlert(<span class="Number">200</span>, <span class="String"><span class="String">&quot;</span>loop iteration <span class="String">&quot;</span></span> <span class="Keyword">+</span> i, __tame_deferrals.<span class="LibraryConstant">defer</span>({}));
__tame_deferrals._fulfill();
})(_next);
} <span class="Keyword">else</span> {
<span class="Keyword">return</span> _break();
}
};
_while(__tame_k);
</pre><script>window.example4 = "for i in [0..3]\n await slowAlert 200, \"loop iteration #{i}\", defer()\n"</script><div class='minibutton load' onclick='javascript: loadConsole(example4);'>load</div><div class='minibutton ok' onclick='javascript: var i, __tame_deferrals, _i, _next, _while,
_this = this;
__tame_k = function() {};
i = 0;
_while = function(__tame_k) {
var _break, _continue;
_break = __tame_k;
_continue = function() {
++i;
return _while(__tame_k);
};
_next = _continue;
if (i <= 3) {
(function(__tame_k) {
__tame_deferrals = new tame.Deferrals(__tame_k);
slowAlert(200, "loop iteration " + i, __tame_deferrals.defer({}));
__tame_deferrals._fulfill();
})(_next);
} else {
return _break();
}
};
_while(__tame_k);
;'>run</div><br class='clear' /></div>
</p>
<p>
To fire those asynchronous calls in parallel, simply exchange
the <tt>for</tt> and <tt>await</tt> blocks:
</p>
<p>
<div class='code'><pre class="idle">await
for i in [0..3]
slowAlert 200, &quot;loop iteration #{i}&quot;, defer()
</pre><pre class="idle"><span class="Storage">var</span> i, __tame_deferrals, __tame_k, _i;
<span class="FunctionName">__tame_k</span> = <span class="Storage">function</span>() {};
__tame_deferrals <span class="Keyword">=</span> <span class="Keyword">new</span> <span class="TypeName">tame.Deferrals</span>(__tame_k);
<span class="Keyword">for</span> (i <span class="Keyword">=</span> _i <span class="Keyword">=</span> <span class="Number">0</span>; _i <span class="Keyword">&lt;=</span> <span class="Number">3</span>; i <span class="Keyword">=</span> <span class="Keyword">++</span>_i) {
slowAlert(<span class="Number">200</span>, <span class="String"><span class="String">&quot;</span>loop iteration <span class="String">&quot;</span></span> <span class="Keyword">+</span> i, __tame_deferrals.<span class="LibraryConstant">defer</span>({}));
}
__tame_deferrals._fulfill();
</pre><script>window.example5 = "await\n for i in [0..3]\n slowAlert 200, \"loop iteration #{i}\", defer()\n"</script><div class='minibutton load' onclick='javascript: loadConsole(example5);'>load</div><div class='minibutton ok' onclick='javascript: var i, __tame_deferrals, __tame_k, _i;
__tame_k = function() {};
__tame_deferrals = new tame.Deferrals(__tame_k);
for (i = _i = 0; _i <= 3; i = ++_i) {
slowAlert(200, "loop iteration " + i, __tame_deferrals.defer({}));
}
__tame_deferrals._fulfill();
;'>run</div><br class='clear' /></div>
</p>
Things start to get interesting when you combine parallel and
serial control flow, but the syntax remains the same:
<p>
<div class='code'><pre class="idle">for i in [0..2]
await
slowAlert 100, &quot;fast alert #{i}&quot;, defer()
slowAlert 200, &quot;slow alert #{i}&quot;, defer()
</pre><pre class="idle"><span class="Storage">var</span> i, __tame_deferrals, _i, _next, _while,
_this <span class="Keyword">=</span> <span class="Variable">this</span>;
<span class="FunctionName">__tame_k</span> = <span class="Storage">function</span>() {};
i <span class="Keyword">=</span> <span class="Number">0</span>;
<span class="FunctionName">_while</span> = <span class="Storage">function</span>(<span class="FunctionArgument">__tame_k</span>) {
<span class="Storage">var</span> _break, _continue;
_break <span class="Keyword">=</span> __tame_k;
<span class="FunctionName">_continue</span> = <span class="Storage">function</span>() {
<span class="Keyword">++</span>i;
<span class="Keyword">return</span> _while(__tame_k);
};
_next <span class="Keyword">=</span> _continue;
<span class="Keyword">if</span> (i <span class="Keyword">&lt;=</span> <span class="Number">2</span>) {
(<span class="Storage">function</span>(__tame_k) {
__tame_deferrals <span class="Keyword">=</span> <span class="Keyword">new</span> <span class="TypeName">tame.Deferrals</span>(__tame_k);
slowAlert(<span class="Number">100</span>, <span class="String"><span class="String">&quot;</span>fast alert <span class="String">&quot;</span></span> <span class="Keyword">+</span> i, __tame_deferrals.<span class="LibraryConstant">defer</span>({}));
slowAlert(<span class="Number">200</span>, <span class="String"><span class="String">&quot;</span>slow alert <span class="String">&quot;</span></span> <span class="Keyword">+</span> i, __tame_deferrals.<span class="LibraryConstant">defer</span>({}));
__tame_deferrals._fulfill();
})(_next);
} <span class="Keyword">else</span> {
<span class="Keyword">return</span> _break();
}
};
_while(__tame_k);
</pre><script>window.example6 = "for i in [0..2]\n await\n slowAlert 100, \"fast alert #{i}\", defer()\n slowAlert 200, \"slow alert #{i}\", defer()\n\n"</script><div class='minibutton load' onclick='javascript: loadConsole(example6);'>load</div><div class='minibutton ok' onclick='javascript: var i, __tame_deferrals, _i, _next, _while,
_this = this;
__tame_k = function() {};
i = 0;
_while = function(__tame_k) {
var _break, _continue;
_break = __tame_k;
_continue = function() {
++i;
return _while(__tame_k);
};
_next = _continue;
if (i <= 2) {
(function(__tame_k) {
__tame_deferrals = new tame.Deferrals(__tame_k);
slowAlert(100, "fast alert " + i, __tame_deferrals.defer({}));
slowAlert(200, "slow alert " + i, __tame_deferrals.defer({}));
__tame_deferrals._fulfill();
})(_next);
} else {
return _break();
}
};
_while(__tame_k);
;'>run</div><br class='clear' /></div>
</p>
<p>
<span id ="tame_defer" class = "bookmark"></span>
<b class="header">Tame Defer Values</b>
Many JS and coffee libraries use callbacks passed as parameters
to signify when the given operation has completed, and which values
were produced. As such, <tt>defer</tt> can take one or more arguments
which are filled in after a deferral is fulfilled. Note that the
snippet below is <i>node.js</i> code that requires a DNS resolver:
<p>
<div class='code'><pre class="idle">dns = require 'dns' # Use node.js's DNS resolution system
for host in [ 'yahoo.com', 'google.com', 'nytimes.com']
await dns.resolve host, &quot;A&quot;, defer err, ip
if err then console.log &quot;Error for #{host}: #{err}&quot;
else console.log &quot;Resolved #{host} -&gt; #{ip}&quot;
</pre><pre class="idle"><span class="Storage">var</span> dns, err, host, ip, __tame_deferrals, _i, _len, _next, _ref, _while,
_this <span class="Keyword">=</span> <span class="Variable">this</span>;
<span class="FunctionName">__tame_k</span> = <span class="Storage">function</span>() {};
dns <span class="Keyword">=</span> require(<span class="String"><span class="String">'</span>dns<span class="String">'</span></span>);
_ref <span class="Keyword">=</span> [<span class="String"><span class="String">'</span>yahoo.com<span class="String">'</span></span>, <span class="String"><span class="String">'</span>google.com<span class="String">'</span></span>, <span class="String"><span class="String">'</span>nytimes.com<span class="String">'</span></span>];
_len <span class="Keyword">=</span> _ref.<span class="LibraryConstant">length</span>;
_i <span class="Keyword">=</span> <span class="Number">0</span>;
<span class="FunctionName">_while</span> = <span class="Storage">function</span>(<span class="FunctionArgument">__tame_k</span>) {
<span class="Storage">var</span> _break, _continue;
_break <span class="Keyword">=</span> __tame_k;
<span class="FunctionName">_continue</span> = <span class="Storage">function</span>() {
<span class="Keyword">++</span>_i;
<span class="Keyword">return</span> _while(__tame_k);
};
_next <span class="Keyword">=</span> _continue;
<span class="Keyword">if</span> (_i <span class="Keyword">&lt;</span> _len) {
host <span class="Keyword">=</span> _ref[_i];
(<span class="Storage">function</span>(__tame_k) {
__tame_deferrals <span class="Keyword">=</span> <span class="Keyword">new</span> <span class="TypeName">tame.Deferrals</span>(__tame_k);
dns.resolve(host, <span class="String"><span class="String">&quot;</span>A<span class="String">&quot;</span></span>, __tame_deferrals.<span class="LibraryConstant">defer</span>({
assign_fn: (<span class="Storage">function</span>() {
<span class="Keyword">return</span> <span class="Storage">function</span>() {
err <span class="Keyword">=</span> arguments[<span class="Number">0</span>];
<span class="Keyword">return</span> ip <span class="Keyword">=</span> arguments[<span class="Number">1</span>];
};
})()
}));
__tame_deferrals._fulfill();
})(<span class="Storage">function</span>() {
<span class="Keyword">return</span> _next(err ? <span class="TypeName">console</span><span class="LibraryFunction">.log</span>(<span class="String"><span class="String">&quot;</span>Error for <span class="String">&quot;</span></span> <span class="Keyword">+</span> host <span class="Keyword">+</span> <span class="String"><span class="String">&quot;</span>: <span class="String">&quot;</span></span> <span class="Keyword">+</span> err) : <span class="TypeName">console</span><span class="LibraryFunction">.log</span>(<span class="String"><span class="String">&quot;</span>Resolved <span class="String">&quot;</span></span> <span class="Keyword">+</span> host <span class="Keyword">+</span> <span class="String"><span class="String">&quot;</span> -&gt; <span class="String">&quot;</span></span> <span class="Keyword">+</span> ip));
});
} <span class="Keyword">else</span> {
<span class="Keyword">return</span> _break();
}
};
_while(__tame_k);
</pre><script>window.example7 = "dns = require 'dns' # Use node.js's DNS resolution system\nfor host in [ 'yahoo.com', 'google.com', 'nytimes.com']\n await dns.resolve host, \"A\", defer err, ip\n if err then console.log \"Error for #{host}: #{err}\"\n else console.log \"Resolved #{host} -> #{ip}\"\n \n"</script><div class='minibutton load' onclick='javascript: loadConsole(example7);'>load</div><br class='clear' /></div>
</p>
<p>
<span id="tame_expr" class = "bookmark"></span>
<b class="header">Tame in an Expression Context</b>
It's possible
to use <tt>await</tt> blocks as expressions. And recursively
speaking, it's possible to use statements that contain `await`
blocks as expressions.
</p>
<p>
The simple rule is that an <tt>await</tt> block takes on the value of the
<tt>defer</tt> slot named <tt>_</tt> after its been fulfilled. If there
are multiple defer slots named <tt>_</tt> within the await block, then
the last writer wins. In practice, there's usually only one. Thus:
</p>
<p><div class='code'><pre class="idle">window.add = (a,b,cb) -&gt;
await setTimeout defer(), 10
cb(a+b)
x = (await add 3, 4, defer _) + (await add 1, 2, defer _)
alert &quot;#{x} is 10&quot;
</pre><pre class="idle"><span class="Storage">var</span> x, __tame_deferrals,
_this <span class="Keyword">=</span> <span class="Variable">this</span>;
<span class="FunctionName">__tame_k</span> = <span class="Storage">function</span>() {};
<span class="LibraryClassType">window</span>.<span class="FunctionName">add</span> = <span class="Storage">function</span>(<span class="FunctionArgument">a, b, cb</span>) {
<span class="Storage">var</span> __tame_deferrals,
_this <span class="Keyword">=</span> <span class="Variable">this</span>;
(<span class="Storage">function</span>(__tame_k) {
__tame_deferrals <span class="Keyword">=</span> <span class="Keyword">new</span> <span class="TypeName">tame.Deferrals</span>(__tame_k);
<span class="LibraryFunction">setTimeout</span>(__tame_deferrals.<span class="LibraryConstant">defer</span>({}), <span class="Number">10</span>);
__tame_deferrals._fulfill();
})(<span class="Storage">function</span>() {
<span class="Keyword">return</span> cb(a <span class="Keyword">+</span> b);
});
};
(<span class="Storage">function</span>(__tame_k) {
<span class="Keyword">return</span> (<span class="Storage">function</span>(__tame_k) {
__tame_deferrals <span class="Keyword">=</span> <span class="Keyword">new</span> <span class="TypeName">tame.Deferrals</span>(__tame_k);
<span class="LibraryFunction">add</span>(<span class="Number">3</span>, <span class="Number">4</span>, __tame_deferrals.<span class="LibraryConstant">defer</span>({
assign_fn: (<span class="Storage">function</span>() {
<span class="Keyword">return</span> <span class="Storage">function</span>() {
<span class="Keyword">return</span> __tame_deferrals.ret <span class="Keyword">=</span> arguments[<span class="Number">0</span>];
};
})()
}));
__tame_deferrals._fulfill();
})(<span class="Storage">function</span>(___tame_p__2) {
<span class="Keyword">return</span> (<span class="Storage">function</span>(__tame_k) {
__tame_deferrals <span class="Keyword">=</span> <span class="Keyword">new</span> <span class="TypeName">tame.Deferrals</span>(__tame_k);
<span class="LibraryFunction">add</span>(<span class="Number">1</span>, <span class="Number">2</span>, __tame_deferrals.<span class="LibraryConstant">defer</span>({
assign_fn: (<span class="Storage">function</span>() {
<span class="Keyword">return</span> <span class="Storage">function</span>() {
<span class="Keyword">return</span> __tame_deferrals.ret <span class="Keyword">=</span> arguments[<span class="Number">0</span>];
};
})()
}));
__tame_deferrals._fulfill();
})(<span class="Storage">function</span>(___tame_p__1) {
<span class="Keyword">return</span> __tame_k(___tame_p__2 <span class="Keyword">+</span> ___tame_p__1);
});
});
})(<span class="Storage">function</span>(___tame_p__0) {
x <span class="Keyword">=</span> ___tame_p__0;
<span class="Keyword">return</span> <span class="LibraryFunction">alert</span>(<span class="String"><span class="String">&quot;</span><span class="String">&quot;</span></span> <span class="Keyword">+</span> x <span class="Keyword">+</span> <span class="String"><span class="String">&quot;</span> is 10<span class="String">&quot;</span></span>);
});;
</pre><script>window.example8 = "window.add = (a,b,cb) ->\n await setTimeout defer(), 10\n cb(a+b)\nx = (await add 3, 4, defer _) + (await add 1, 2, defer _)\nalert \"#{x} is 10\"\n"</script><div class='minibutton load' onclick='javascript: loadConsole(example8);'>load</div><div class='minibutton ok' onclick='javascript: var x, __tame_deferrals,
_this = this;
__tame_k = function() {};
window.add = function(a, b, cb) {
var __tame_deferrals,
_this = this;
(function(__tame_k) {
__tame_deferrals = new tame.Deferrals(__tame_k);
setTimeout(__tame_deferrals.defer({}), 10);
__tame_deferrals._fulfill();
})(function() {
return cb(a + b);
});
};
(function(__tame_k) {
return (function(__tame_k) {
__tame_deferrals = new tame.Deferrals(__tame_k);
add(3, 4, __tame_deferrals.defer({
assign_fn: (function() {
return function() {
return __tame_deferrals.ret = arguments[0];
};
})()
}));
__tame_deferrals._fulfill();
})(function(___tame_p__2) {
return (function(__tame_k) {
__tame_deferrals = new tame.Deferrals(__tame_k);
add(1, 2, __tame_deferrals.defer({
assign_fn: (function() {
return function() {
return __tame_deferrals.ret = arguments[0];
};
})()
}));
__tame_deferrals._fulfill();
})(function(___tame_p__1) {
return __tame_k(___tame_p__2 + ___tame_p__1);
});
});
})(function(___tame_p__0) {
x = ___tame_p__0;
return alert("" + x + " is 10");
});;
;'>run</div><br class='clear' /></div></p>
<p>
Of course, things can get arbitrarily compicated and nested, so it
gets hairy. Consider this:
</p>
<p><div class='code'><pre class="idle">x = await add (await add 1, 2, defer _), (await add 3, 4, defer _), defer _
</pre><pre class="idle"><span class="Storage">var</span> x, __tame_deferrals,
_this <span class="Keyword">=</span> <span class="Variable">this</span>;
<span class="FunctionName">__tame_k</span> = <span class="Storage">function</span>() {};
(<span class="Storage">function</span>(__tame_k) {
(<span class="Storage">function</span>(__tame_k) {
__tame_deferrals <span class="Keyword">=</span> <span class="Keyword">new</span> <span class="TypeName">tame.Deferrals</span>(__tame_k);
<span class="LibraryFunction">add</span>(<span class="Number">1</span>, <span class="Number">2</span>, __tame_deferrals.<span class="LibraryConstant">defer</span>({
assign_fn: (<span class="Storage">function</span>() {
<span class="Keyword">return</span> <span class="Storage">function</span>() {
<span class="Keyword">return</span> __tame_deferrals.ret <span class="Keyword">=</span> arguments[<span class="Number">0</span>];
};
})()
}));
__tame_deferrals._fulfill();
})(<span class="Storage">function</span>(___tame_p__5) {
<span class="Keyword">return</span> (<span class="Storage">function</span>(__tame_k) {
__tame_deferrals <span class="Keyword">=</span> <span class="Keyword">new</span> <span class="TypeName">tame.Deferrals</span>(__tame_k);
<span class="LibraryFunction">add</span>(<span class="Number">3</span>, <span class="Number">4</span>, __tame_deferrals.<span class="LibraryConstant">defer</span>({
assign_fn: (<span class="Storage">function</span>() {
<span class="Keyword">return</span> <span class="Storage">function</span>() {
<span class="Keyword">return</span> __tame_deferrals.ret <span class="Keyword">=</span> arguments[<span class="Number">0</span>];
};
})()
}));
__tame_deferrals._fulfill();
})(<span class="Storage">function</span>(___tame_p__4) {
__tame_deferrals <span class="Keyword">=</span> <span class="Keyword">new</span> <span class="TypeName">tame.Deferrals</span>(__tame_k);
<span class="LibraryFunction">add</span>(___tame_p__5, ___tame_p__4, __tame_deferrals.<span class="LibraryConstant">defer</span>({
assign_fn: (<span class="Storage">function</span>() {
<span class="Keyword">return</span> <span class="Storage">function</span>() {
<span class="Keyword">return</span> __tame_deferrals.ret <span class="Keyword">=</span> arguments[<span class="Number">0</span>];
};
})()
}));
__tame_deferrals._fulfill();
});
});
})(<span class="Storage">function</span>(___tame_p__3) {
<span class="Keyword">return</span> x <span class="Keyword">=</span> ___tame_p__3;
});;
</pre><script>window.example9 = "x = await add (await add 1, 2, defer _), (await add 3, 4, defer _), defer _\n"</script><div class='minibutton load' onclick='javascript: loadConsole(example9);'>load</div><div class='minibutton ok' onclick='javascript: var x, __tame_deferrals,
_this = this;
__tame_k = function() {};
(function(__tame_k) {
(function(__tame_k) {
__tame_deferrals = new tame.Deferrals(__tame_k);
add(1, 2, __tame_deferrals.defer({
assign_fn: (function() {
return function() {
return __tame_deferrals.ret = arguments[0];
};
})()
}));
__tame_deferrals._fulfill();
})(function(___tame_p__5) {
return (function(__tame_k) {
__tame_deferrals = new tame.Deferrals(__tame_k);
add(3, 4, __tame_deferrals.defer({
assign_fn: (function() {
return function() {
return __tame_deferrals.ret = arguments[0];
};
})()
}));
__tame_deferrals._fulfill();
})(function(___tame_p__4) {
__tame_deferrals = new tame.Deferrals(__tame_k);
add(___tame_p__5, ___tame_p__4, __tame_deferrals.defer({
assign_fn: (function() {
return function() {
return __tame_deferrals.ret = arguments[0];
};
})()
}));
__tame_deferrals._fulfill();
});
});
})(function(___tame_p__3) {
return x = ___tame_p__3;
});;
;'>run</div><br class='clear' /></div></p>
<p>
The rule is that all nested <tt>await</tt> blocks (barf!) are evaluated
sequentially in DFS order. You will get <tt>10</tt> in the above example
after three sequential calls to <tt>add</tt>.
</p>
<p>
I really don't like this feature for two reasons: (1) it's tricky to
get the implementation right, and I'm sure I haven't tested all of the
corner cases yet; (2) it's difficult to read and understand what
happens in which order. I would suggest you save yourself the heartache,
and just write the above as this:
</p>
<p><div class='code'><pre class="idle">await add 1, 2, defer l
await add 3, 4, defer r
await add l, r, defer x
</pre><pre class="idle"><span class="Storage">var</span> l, r, x, __tame_deferrals,
_this <span class="Keyword">=</span> <span class="Variable">this</span>;
<span class="FunctionName">__tame_k</span> = <span class="Storage">function</span>() {};
(<span class="Storage">function</span>(__tame_k) {
__tame_deferrals <span class="Keyword">=</span> <span class="Keyword">new</span> <span class="TypeName">tame.Deferrals</span>(__tame_k);
<span class="LibraryFunction">add</span>(<span class="Number">1</span>, <span class="Number">2</span>, __tame_deferrals.<span class="LibraryConstant">defer</span>({
assign_fn: (<span class="Storage">function</span>() {
<span class="Keyword">return</span> <span class="Storage">function</span>() {
<span class="Keyword">return</span> l <span class="Keyword">=</span> arguments[<span class="Number">0</span>];
};
})()
}));
__tame_deferrals._fulfill();
})(<span class="Storage">function</span>() {
(<span class="Storage">function</span>(__tame_k) {
__tame_deferrals <span class="Keyword">=</span> <span class="Keyword">new</span> <span class="TypeName">tame.Deferrals</span>(__tame_k);
<span class="LibraryFunction">add</span>(<span class="Number">3</span>, <span class="Number">4</span>, __tame_deferrals.<span class="LibraryConstant">defer</span>({
assign_fn: (<span class="Storage">function</span>() {
<span class="Keyword">return</span> <span class="Storage">function</span>() {
<span class="Keyword">return</span> r <span class="Keyword">=</span> arguments[<span class="Number">0</span>];
};
})()
}));
__tame_deferrals._fulfill();
})(<span class="Storage">function</span>() {
__tame_deferrals <span class="Keyword">=</span> <span class="Keyword">new</span> <span class="TypeName">tame.Deferrals</span>(__tame_k);
<span class="LibraryFunction">add</span>(l, r, __tame_deferrals.<span class="LibraryConstant">defer</span>({
assign_fn: (<span class="Storage">function</span>() {
<span class="Keyword">return</span> <span class="Storage">function</span>() {
<span class="Keyword">return</span> x <span class="Keyword">=</span> arguments[<span class="Number">0</span>];
};
})()
}));
__tame_deferrals._fulfill();
});
});
</pre><script>window.example10 = "await add 1, 2, defer l\nawait add 3, 4, defer r\nawait add l, r, defer x\n"</script><div class='minibutton load' onclick='javascript: loadConsole(example10);'>load</div><div class='minibutton ok' onclick='javascript: var l, r, x, __tame_deferrals,
_this = this;
__tame_k = function() {};
(function(__tame_k) {
__tame_deferrals = new tame.Deferrals(__tame_k);
add(1, 2, __tame_deferrals.defer({
assign_fn: (function() {
return function() {
return l = arguments[0];
};
})()
}));
__tame_deferrals._fulfill();
})(function() {
(function(__tame_k) {
__tame_deferrals = new tame.Deferrals(__tame_k);
add(3, 4, __tame_deferrals.defer({
assign_fn: (function() {
return function() {
return r = arguments[0];
};
})()
}));
__tame_deferrals._fulfill();
})(function() {
__tame_deferrals = new tame.Deferrals(__tame_k);
add(l, r, __tame_deferrals.defer({
assign_fn: (function() {
return function() {
return x = arguments[0];
};
})()
}));
__tame_deferrals._fulfill();
});
});
;'>run</div><br class='clear' /></div></p>
<p>
It's just so much clearer what happens in which order, and it's easier
to parallelize or serialize as you see fit.
</p>
<p>
<span id="literals" class="bookmark"></span>
<b class="header">Functions</b>
Functions are defined by an optional list of parameters in parentheses,
an arrow, and the function body. The empty function looks like this:
<tt>-></tt>
</p>
<div class='code'><pre class="idle">square = (x) -&gt; x * x
cube = (x) -&gt; square(x) * 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><script>window.example11 = "square = (x) -> x * x\ncube = (x) -> square(x) * x\n\nalert cube(5)"</script><div class='minibutton load' onclick='javascript: loadConsole(example11);'>load</div><div class='minibutton ok' onclick='javascript: var cube, square;
square = function(x) {
return x * x;
};
cube = function(x) {
return square(x) * x;
};
;alert(cube(5));'>run: cube(5)</div><br class='clear' /></div>
<p>
Functions may also have default values for arguments. Override the default
value by passing a non-null argument.
</p>
<div class='code'><pre class="idle">fill = (container, liquid = &quot;coffee&quot;) -&gt;
&quot;Filling the #{container} with #{liquid}...&quot;
</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><script>window.example12 = "fill = (container, liquid = \"coffee\") ->\n \"Filling the #{container} with #{liquid}...\"\n\nalert fill(\"cup\")"</script><div class='minibutton load' onclick='javascript: loadConsole(example12);'>load</div><div class='minibutton ok' onclick='javascript: var fill;
fill = function(container, liquid) {
if (liquid == null) liquid = "coffee";
return "Filling the " + container + " with " + liquid + "...";
};
;alert(fill("cup"));'>run: fill("cup")</div><br class='clear' /></div>
<p>
<span id="objects_and_arrays" class="bookmark"></span>
<b class="header">Objects and Arrays</b>
The CoffeeScript literals for objects and arrays look very similar to
their JavaScript cousins. When each property is listed on its own line,
the commas are optional. Objects may be created using indentation instead
of explicit braces, similar to <a href="http://yaml.org">YAML</a>.
</p>
<div class='code'><pre class="idle">song = [&quot;do&quot;, &quot;re&quot;, &quot;mi&quot;, &quot;fa&quot;, &quot;so&quot;]
singers = {Jagger: &quot;Rock&quot;, Elvis: &quot;Roll&quot;}
bitlist = [
1, 0, 1
0, 0, 1
1, 1, 0
]
kids =
brother:
name: &quot;Max&quot;
age: 11
sister:
name: &quot;Ida&quot;
age: 9
</pre><pre class="idle"><span class="Storage">var</span> bitlist, kids, 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>
};
bitlist <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><script>window.example13 = "song = [\"do\", \"re\", \"mi\", \"fa\", \"so\"]\n\nsingers = {Jagger: \"Rock\", Elvis: \"Roll\"}\n\nbitlist = [\n 1, 0, 1\n 0, 0, 1\n 1, 1, 0\n]\n\nkids =\n brother:\n name: \"Max\"\n age: 11\n sister:\n name: \"Ida\"\n age: 9\n\nalert song.join(\" ... \")"</script><div class='minibutton load' onclick='javascript: loadConsole(example13);'>load</div><div class='minibutton ok' onclick='javascript: var bitlist, kids, singers, song;
song = ["do", "re", "mi", "fa", "so"];
singers = {
Jagger: "Rock",
Elvis: "Roll"
};
bitlist = [1, 0, 1, 0, 0, 1, 1, 1, 0];
kids = {
brother: {
name: "Max",
age: 11
},
sister: {
name: "Ida",
age: 9
}
};
;alert(song.join(" ... "));'>run: song.join(" ... ")</div><br class='clear' /></div>
<p>
In JavaScript, you can't use reserved words, like <tt>class</tt>, as properties
of an object, without quoting them as strings. CoffeeScript notices reserved words
used as keys in objects and quotes them for you, so you don't have to worry
about it (say, when using jQuery).
</p>
<div class='code'><pre class="idle">$('.account').attr class: 'active'
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><script>window.example14 = "$('.account').attr class: 'active'\n\nlog object.class\n\n\n"</script><div class='minibutton load' onclick='javascript: loadConsole(example14);'>load</div><br class='clear' /></div>
<p>
<span id="lexical_scope" class="bookmark"></span>
<b class="header">Lexical Scoping and Variable Safety</b>
The CoffeeScript compiler takes care to make sure that all of your variables
are properly declared within lexical scope &mdash; you never need to write
<tt>var</tt> yourself.
</p>
<div class='code'><pre class="idle">outer = 1
changeNumbers = -&gt;
inner = -1
outer = 10
inner = 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><script>window.example15 = "outer = 1\nchangeNumbers = ->\n inner = -1\n outer = 10\ninner = changeNumbers()\n\nalert inner"</script><div class='minibutton load' onclick='javascript: loadConsole(example15);'>load</div><div class='minibutton ok' onclick='javascript: var changeNumbers, inner, outer;
outer = 1;
changeNumbers = function() {
var inner;
inner = -1;
return outer = 10;
};
inner = changeNumbers();
;alert(inner);'>run: inner</div><br class='clear' /></div>
<p>
Notice how all of the variable declarations have been pushed up to
the top of the closest scope, the first time they appear.
<b>outer</b> is not redeclared within the inner function, because it's
already in scope; <b>inner</b> within the function, on the other hand,
should not be able to change the value of the external variable of the same name, and
therefore has a declaration of its own.
</p>
<p>
This behavior is effectively identical to Ruby's scope for local variables.
Because you don't have direct access to the <tt>var</tt> keyword,
it's impossible to shadow an outer variable on purpose, you may only refer
to it. So be careful that you're not reusing the name of an external
variable accidentally, if you're writing a deeply nested function.
</p>
<p>
Although suppressed within this documentation for clarity, all
CoffeeScript output is wrapped in an anonymous function:
<tt>(function(){ ... })();</tt> This safety wrapper, combined with the
automatic generation of the <tt>var</tt> keyword, make it exceedingly difficult
to pollute the global namespace by accident.
</p>
<p>
If you'd like to create top-level variables for other scripts to use,
attach them as properties on <b>window</b>, or on the <b>exports</b>
object in CommonJS. The <b>existential operator</b> (covered below), gives you a
reliable way to figure out where to add them; if you're targeting both
CommonJS and the browser: <tt>exports ? this</tt>
</p>
<p>
<span id="conditionals" class="bookmark"></span>
<b class="header">If, Else, Unless, and Conditional Assignment</b>
<b>If/else</b> statements can be written without the use of parentheses and
curly brackets. As with functions and other block expressions,
multi-line conditionals are delimited by indentation. There's also a handy
postfix form, with the <tt>if</tt> or <tt>unless</tt> at the end.
</p>
<p>
CoffeeScript can compile <b>if</b> statements into JavaScript expressions,
using the ternary operator when possible, and closure wrapping otherwise. There
is no explicit ternary statement in CoffeeScript &mdash; you simply use
a regular <b>if</b> statement on a single line.
</p>
<div class='code'><pre class="idle">mood = greatlyImproved if singing
if happy and knowsIt
clapsHands()
chaChaCha()
else
showIt()
date = if friday then sue else jill
options or= 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><script>window.example16 = "mood = greatlyImproved if singing\n\nif happy and knowsIt\n clapsHands()\n chaChaCha()\nelse\n showIt()\n\ndate = if friday then sue else jill\n\noptions or= defaults\n\n\n"</script><div class='minibutton load' onclick='javascript: loadConsole(example16);'>load</div><br class='clear' /></div>
<p>
<span id="splats" class="bookmark"></span>
<b class="header">Splats...</b>
The JavaScript <b>arguments object</b> is a useful way to work with
functions that accept variable numbers of arguments. CoffeeScript provides
splats <tt>...</tt>, both for function definition as well as invocation,
making variable numbers of arguments a little bit more palatable.
</p>
<div class='code'><pre class="idle">gold = silver = rest = &quot;unknown&quot;
awardMedals = (first, second, others...) -&gt;
gold = first
silver = second
rest = others
contenders = [
&quot;Michael Phelps&quot;
&quot;Liu Xiang&quot;
&quot;Yao Ming&quot;
&quot;Allyson Felix&quot;
&quot;Shawn Johnson&quot;
&quot;Roman Sebrle&quot;
&quot;Guo Jingjing&quot;
&quot;Tyson Gay&quot;
&quot;Asafa Powell&quot;
&quot;Usain Bolt&quot;
]
awardMedals contenders...
alert &quot;Gold: &quot; + gold
alert &quot;Silver: &quot; + silver
alert &quot;The Field: &quot; + rest
</pre><pre class="idle"><span class="Storage">var</span> awardMedals, contenders, gold, rest, silver,
__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>(<span class="BuiltInConstant">null</span>, 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><script>window.example17 = "gold = silver = rest = \"unknown\"\n\nawardMedals = (first, second, others...) ->\n gold = first\n silver = second\n rest = others\n\ncontenders = [\n \"Michael Phelps\"\n \"Liu Xiang\"\n \"Yao Ming\"\n \"Allyson Felix\"\n \"Shawn Johnson\"\n \"Roman Sebrle\"\n \"Guo Jingjing\"\n \"Tyson Gay\"\n \"Asafa Powell\"\n \"Usain Bolt\"\n]\n\nawardMedals contenders...\n\nalert \"Gold: \" + gold\nalert \"Silver: \" + silver\nalert \"The Field: \" + rest\n\n\n"</script><div class='minibutton load' onclick='javascript: loadConsole(example17);'>load</div><div class='minibutton ok' onclick='javascript: var awardMedals, contenders, gold, rest, silver,
__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(null, contenders);
alert("Gold: " + gold);
alert("Silver: " + silver);
alert("The Field: " + rest);
;'>run</div><br class='clear' /></div>
<p>
<span id="loops" class="bookmark"></span>
<b class="header">Loops and Comprehensions</b>
Most of the loops you'll write in CoffeeScript will be <b>comprehensions</b>
over arrays, objects, and ranges. Comprehensions replace (and compile into)
<b>for</b> loops, with optional guard clauses and the value of the current array index.
Unlike for loops, array comprehensions are expressions, and can be returned
and assigned.
</p>
<div class='code'><pre class="idle"># Eat lunch.
eat food for food in ['toast', 'cheese', 'wine']
# Fine five course dining.
courses = ['greens', 'caviar', 'truffles', 'roast', 'cake']
menu i + 1, dish for dish, i in courses
# Health conscious meal.
foods = ['broccoli', 'spinach', 'chocolate']
eat food for food in foods when food isnt 'chocolate'
</pre><pre class="idle"><span class="Storage">var</span> courses, dish, food, foods, i, _i, _j, _k, _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];
eat(food);
}
courses <span class="Keyword">=</span> [<span class="String"><span class="String">'</span>greens<span class="String">'</span></span>, <span class="String"><span class="String">'</span>caviar<span class="String">'</span></span>, <span class="String"><span class="String">'</span>truffles<span class="String">'</span></span>, <span class="String"><span class="String">'</span>roast<span class="String">'</span></span>, <span class="String"><span class="String">'</span>cake<span class="String">'</span></span>];
<span class="Keyword">for</span> (i <span class="Keyword">=</span> _j <span class="Keyword">=</span> <span class="Number">0</span>, _len2 <span class="Keyword">=</span> courses.<span class="LibraryConstant">length</span>; _j <span class="Keyword">&lt;</span> _len2; i <span class="Keyword">=</span> <span class="Keyword">++</span>_j) {
dish <span class="Keyword">=</span> courses[i];
menu(i <span class="Keyword">+</span> <span class="Number">1</span>, dish);
}
foods <span class="Keyword">=</span> [<span class="String"><span class="String">'</span>broccoli<span class="String">'</span></span>, <span class="String"><span class="String">'</span>spinach<span class="String">'</span></span>, <span class="String"><span class="String">'</span>chocolate<span class="String">'</span></span>];
<span class="Keyword">for</span> (_k <span class="Keyword">=</span> <span class="Number">0</span>, _len3 <span class="Keyword">=</span> foods.<span class="LibraryConstant">length</span>; _k <span class="Keyword">&lt;</span> _len3; _k<span class="Keyword">++</span>) {
food <span class="Keyword">=</span> foods[_k];
<span class="Keyword">if</span> (food <span class="Keyword">!</span><span class="Keyword">==</span> <span class="String"><span class="String">'</span>chocolate<span class="String">'</span></span>) eat(food);
}
</pre><script>window.example18 = "# Eat lunch.\neat food for food in ['toast', 'cheese', 'wine']\n\n# Fine five course dining.\ncourses = ['greens', 'caviar', 'truffles', 'roast', 'cake']\nmenu i + 1, dish for dish, i in courses\n\n# Health conscious meal.\nfoods = ['broccoli', 'spinach', 'chocolate']\neat food for food in foods when food isnt 'chocolate'\n"</script><div class='minibutton load' onclick='javascript: loadConsole(example18);'>load</div><br class='clear' /></div>
<p>
Comprehensions should be able to handle most places where you otherwise
would use a loop, <b>each</b>/<b>forEach</b>, <b>map</b>, or <b>select</b>/<b>filter</b>, for example:
<tt>shortNames = (name for name in list when name.length &lt; 5)</tt><br />
If you know the start and end of your loop, or would like to step through
in fixed-size increments, you can use a range to specify the start and
end of your comprehension.
</p>
<div class='code'><pre class="idle">countdown = (num for num in [10..1])
</pre><pre class="idle"><span class="Storage">var</span> countdown, num;
countdown <span class="Keyword">=</span> (<span class="Storage">function</span>() {
<span class="Storage">var</span> _i, _results;
_results <span class="Keyword">=</span> [];
<span class="Keyword">for</span> (num <span class="Keyword">=</span> _i <span class="Keyword">=</span> <span class="Number">10</span>; _i <span class="Keyword">&gt;=</span> <span class="Number">1</span>; num <span class="Keyword">=</span> <span class="Keyword">--</span>_i) {
_results.<span class="LibraryFunction">push</span>(num);
}
<span class="Keyword">return</span> _results;
})();
</pre><script>window.example19 = "countdown = (num for num in [10..1])\n\nalert countdown"</script><div class='minibutton load' onclick='javascript: loadConsole(example19);'>load</div><div class='minibutton ok' onclick='javascript: var countdown, num;
countdown = (function() {
var _i, _results;
_results = [];
for (num = _i = 10; _i >= 1; num = --_i) {
_results.push(num);
}
return _results;
})();
;alert(countdown);'>run: countdown</div><br class='clear' /></div>
<p>
Note how because we are assigning the value of the comprehensions to a
variable in the example above, CoffeeScript is collecting the result of
each iteration into an array. Sometimes functions end with loops that are
intended to run only for their side-effects. Be careful that you're not
accidentally returning the results of the comprehension in these cases,
by adding a meaningful return value &mdash; like <tt>true</tt> &mdash; or <tt>null</tt>,
to the bottom of your function.
</p>
<p>
To step through a range comprehension in fixed-size chunks,
use <tt>by</tt>, for example:<br />
<tt>evens = (x for x in [0..10] by 2)</tt>
</p>
<p>
Comprehensions can also be used to iterate over the keys and values in
an object. Use <tt>of</tt> to signal comprehension over the properties of
an object instead of the values in an array.
</p>
<div class='code'><pre class="idle">yearsOld = max: 10, ida: 9, tim: 11
ages = for child, age of yearsOld
&quot;#{child} is #{age}&quot;
</pre><pre class="idle"><span class="Storage">var</span> age, ages, child, yearsOld;
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="Storage">function</span>() {
<span class="Storage">var</span> _results;
_results <span class="Keyword">=</span> [];
<span class="Keyword">for</span> (child <span class="Keyword">in</span> yearsOld) {
age <span class="Keyword">=</span> yearsOld[child];
_results.<span class="LibraryFunction">push</span>(<span class="String"><span class="String">&quot;</span><span class="String">&quot;</span></span> <span class="Keyword">+</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><script>window.example20 = "yearsOld = max: 10, ida: 9, tim: 11\n\nages = for child, age of yearsOld\n \"#{child} is #{age}\"\n\nalert ages.join(\", \")"</script><div class='minibutton load' onclick='javascript: loadConsole(example20);'>load</div><div class='minibutton ok' onclick='javascript: var age, ages, child, yearsOld;
yearsOld = {
max: 10,
ida: 9,
tim: 11
};
ages = (function() {
var _results;
_results = [];
for (child in yearsOld) {
age = yearsOld[child];
_results.push("" + child + " is " + age);
}
return _results;
})();
;alert(ages.join(", "));'>run: ages.join(", ")</div><br class='clear' /></div>
<p>
If you would like to iterate over just the keys that are defined on the
object itself, by adding a <tt>hasOwnProperty</tt>
check to avoid properties that may be inherited from the prototype, use<br />
<tt>for own key, value of object</tt>
</p>
<p>
The only low-level loop that CoffeeScript provides is the <b>while</b> loop. The
main difference from JavaScript is that the <b>while</b> loop can be used
as an expression, returning an array containing the result of each iteration
through the loop.
</p>
<div class='code'><pre class="idle"># Econ 101
if this.studyingEconomics
buy() while supply &gt; demand
sell() until supply &gt; demand
# Nursery Rhyme
num = 6
lyrics = while num -= 1
&quot;#{num} little monkeys, jumping on the bed.
One fell out and bumped his head.&quot;
</pre><pre class="idle"><span class="Storage">var</span> lyrics, num;
<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> (<span class="Keyword">!</span>(supply <span class="Keyword">&gt;</span> demand)) {
sell();
}
}
num <span class="Keyword">=</span> <span class="Number">6</span>;
lyrics <span class="Keyword">=</span> (<span class="Storage">function</span>() {
<span class="Storage">var</span> _results;
_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>(<span class="String"><span class="String">&quot;</span><span class="String">&quot;</span></span> <span class="Keyword">+</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><script>window.example21 = "# Econ 101\nif this.studyingEconomics\n buy() while supply > demand\n sell() until supply > demand\n\n# Nursery Rhyme\nnum = 6\nlyrics = while num -= 1\n \"#{num} little monkeys, jumping on the bed.\n One fell out and bumped his head.\"\n\nalert lyrics.join(\"\\n\")"</script><div class='minibutton load' onclick='javascript: loadConsole(example21);'>load</div><div class='minibutton ok' onclick='javascript: var lyrics, num;
if (this.studyingEconomics) {
while (supply > demand) {
buy();
}
while (!(supply > demand)) {
sell();
}
}
num = 6;
lyrics = (function() {
var _results;
_results = [];
while (num -= 1) {
_results.push("" + num + " little monkeys, jumping on the bed. One fell out and bumped his head.");
}
return _results;
})();
;alert(lyrics.join("\n"));'>run: lyrics.join("\n")</div><br class='clear' /></div>
<p>
For readability, the <b>until</b> keyword is equivalent to <tt>while not</tt>,
and the <b>loop</b> keyword is equivalent to <tt>while true</tt>.
</p>
<p>
When using a JavaScript loop to generate functions, it's common to insert
a closure wrapper in order to ensure that loop variables are closed over,
and all the generated functions don't just share the final values. CoffeeScript
provides the <tt>do</tt> keyword, which immediately invokes a passed function,
forwarding any arguments.
</p>
<div class='code'><pre class="idle">for filename in list
do (filename) -&gt;
fs.readFile filename, (err, contents) -&gt;
compile filename, contents.toString()
</pre><pre class="idle"><span class="Storage">var</span> filename, _fn, _i, _len;
<span class="FunctionName">_fn</span> = <span class="Storage">function</span>(<span class="FunctionArgument">filename</span>) {
<span class="Keyword">return</span> fs.readFile(filename, <span class="Storage">function</span>(err, contents) {
<span class="Keyword">return</span> <span class="LibraryFunction">compile</span>(filename, contents.<span class="LibraryFunction">toString</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>) {
filename <span class="Keyword">=</span> list[_i];
_fn(filename);
}
</pre><script>window.example22 = "for filename in list\n do (filename) ->\n fs.readFile filename, (err, contents) ->\n compile filename, contents.toString()"</script><div class='minibutton load' onclick='javascript: loadConsole(example22);'>load</div><br class='clear' /></div>
<p>
<span id="slices" class="bookmark"></span>
<b class="header">Array Slicing and Splicing with Ranges</b>
Ranges can also be used to extract slices of arrays.
With two dots (<tt>3..6</tt>), the range is inclusive (<tt>3, 4, 5, 6</tt>);
with three dots (<tt>3...6</tt>), the range excludes the end (<tt>3, 4, 5</tt>).
</p>
<div class='code'><pre class="idle">numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
copy = numbers[0...numbers.length]
middle = copy[3..6]
</pre><pre class="idle"><span class="Storage">var</span> copy, middle, numbers;
numbers <span class="Keyword">=</span> [<span class="Number">0</span>, <span class="Number">1</span>, <span class="Number">2</span>, <span class="Number">3</span>, <span class="Number">4</span>, <span class="Number">5</span>, <span class="Number">6</span>, <span class="Number">7</span>, <span class="Number">8</span>, <span class="Number">9</span>];
copy <span class="Keyword">=</span> numbers.<span class="LibraryFunction">slice</span>(<span class="Number">0</span>, numbers.<span class="LibraryConstant">length</span>);
middle <span class="Keyword">=</span> copy.<span class="LibraryFunction">slice</span>(<span class="Number">3</span>, <span class="Number">7</span>);
</pre><script>window.example23 = "numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n\ncopy = numbers[0...numbers.length]\n\nmiddle = copy[3..6]\n\nalert middle"</script><div class='minibutton load' onclick='javascript: loadConsole(example23);'>load</div><div class='minibutton ok' onclick='javascript: var copy, middle, numbers;
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
copy = numbers.slice(0, numbers.length);
middle = copy.slice(3, 7);
;alert(middle);'>run: middle</div><br class='clear' /></div>
<p>
The same syntax can be used with assignment to replace a segment of an array
with new values, splicing it.
</p>
<div class='code'><pre class="idle">numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
numbers[3..6] = [-3, -4, -5, -6]
</pre><pre class="idle"><span class="Storage">var</span> numbers, _ref;
numbers <span class="Keyword">=</span> [<span class="Number">0</span>, <span class="Number">1</span>, <span class="Number">2</span>, <span class="Number">3</span>, <span class="Number">4</span>, <span class="Number">5</span>, <span class="Number">6</span>, <span class="Number">7</span>, <span class="Number">8</span>, <span class="Number">9</span>];
[].splice.<span class="LibraryFunction">apply</span>(numbers, [<span class="Number">3</span>, <span class="Number">4</span>].<span class="LibraryFunction">concat</span>(_ref <span class="Keyword">=</span> [<span class="Keyword">-</span><span class="Number">3</span>, <span class="Keyword">-</span><span class="Number">4</span>, <span class="Keyword">-</span><span class="Number">5</span>, <span class="Keyword">-</span><span class="Number">6</span>])), _ref;
</pre><script>window.example24 = "numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n\nnumbers[3..6] = [-3, -4, -5, -6]\n\nalert numbers"</script><div class='minibutton load' onclick='javascript: loadConsole(example24);'>load</div><div class='minibutton ok' onclick='javascript: var numbers, _ref;
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
[].splice.apply(numbers, [3, 4].concat(_ref = [-3, -4, -5, -6])), _ref;
;alert(numbers);'>run: numbers</div><br class='clear' /></div>
<p>
Note that JavaScript strings are immutable, and can't be spliced.
</p>
<p>
<span id="expressions" class="bookmark"></span>
<b class="header">Everything is an Expression (at least, as much as possible)</b>
You might have noticed how even though we don't add return statements
to CoffeeScript functions, they nonetheless return their final value.
The CoffeeScript compiler tries to make sure that all statements in the
language can be used as expressions. Watch how the <tt>return</tt> gets
pushed down into each possible branch of execution in the function
below.
</p>
<div class='code'><pre class="idle">grade = (student) -&gt;
if student.excellentWork
&quot;A+&quot;
else if student.okayStuff
if student.triedHard then &quot;B&quot; else &quot;B-&quot;
else
&quot;C&quot;
eldest = if 24 &gt; 21 then &quot;Liz&quot; else &quot;Ike&quot;
</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><script>window.example25 = "grade = (student) ->\n if student.excellentWork\n \"A+\"\n else if student.okayStuff\n if student.triedHard then \"B\" else \"B-\"\n else\n \"C\"\n\neldest = if 24 > 21 then \"Liz\" else \"Ike\"\n\nalert eldest"</script><div class='minibutton load' onclick='javascript: loadConsole(example25);'>load</div><div class='minibutton ok' onclick='javascript: var eldest, grade;
grade = function(student) {
if (student.excellentWork) {
return "A+";
} else if (student.okayStuff) {
if (student.triedHard) {
return "B";
} else {
return "B-";
}
} else {
return "C";
}
};
eldest = 24 > 21 ? "Liz" : "Ike";
;alert(eldest);'>run: eldest</div><br class='clear' /></div>
<p>
Even though functions will always return their final value, it's both possible
and encouraged to return early from a function body writing out the explicit
return (<tt>return value</tt>), when you know that you're done.
</p>
<p>
Because variable declarations occur at the top of scope, assignment can
be used within expressions, even for variables that haven't been seen before:
</p>
<div class='code'><pre class="idle">six = (one = 1) + (two = 2) + (three = 3)
</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><script>window.example26 = "six = (one = 1) + (two = 2) + (three = 3)\n\nalert six"</script><div class='minibutton load' onclick='javascript: loadConsole(example26);'>load</div><div class='minibutton ok' onclick='javascript: var one, six, three, two;
six = (one = 1) + (two = 2) + (three = 3);
;alert(six);'>run: six</div><br class='clear' /></div>
<p>
Things that would otherwise be statements in JavaScript, when used
as part of an expression in CoffeeScript, are converted into expressions
by wrapping them in a closure. This lets you do useful things, like assign
the result of a comprehension to a variable:
</p>
<div class='code'><pre class="idle"># The first ten global properties.
globals = (name for name of window)[0...10]
</pre><pre class="idle"><span class="Storage">var</span> globals, name;
globals <span class="Keyword">=</span> ((<span class="Storage">function</span>() {
<span class="Storage">var</span> _results;
_results <span class="Keyword">=</span> [];
<span class="Keyword">for</span> (name <span class="Keyword">in</span> <span class="LibraryClassType">window</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><script>window.example27 = "# The first ten global properties.\n\nglobals = (name for name of window)[0...10]\n\nalert globals"</script><div class='minibutton load' onclick='javascript: loadConsole(example27);'>load</div><div class='minibutton ok' onclick='javascript: var globals, name;
globals = ((function() {
var _results;
_results = [];
for (name in window) {
_results.push(name);
}
return _results;
})()).slice(0, 10);
;alert(globals);'>run: globals</div><br class='clear' /></div>
<p>
As well as silly things, like passing a <b>try/catch</b> statement directly
into a function call:
</p>
<div class='code'><pre class="idle">alert(
try
nonexistent / undefined
catch error
&quot;And the error is ... #{error}&quot;
)
</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><script>window.example28 = "alert(\n try\n nonexistent / undefined\n catch error\n \"And the error is ... #{error}\"\n)\n\n"</script><div class='minibutton load' onclick='javascript: loadConsole(example28);'>load</div><div class='minibutton ok' onclick='javascript:
alert((function() {
try {
return nonexistent / void 0;
} catch (error) {
return "And the error is ... " + error;
}
})());
;'>run</div><br class='clear' /></div>
<p>
There are a handful of statements in JavaScript that can't be meaningfully
converted into expressions, namely <tt>break</tt>, <tt>continue</tt>,
and <tt>return</tt>. If you make use of them within a block of code,
CoffeeScript won't try to perform the conversion.
</p>
<p>
<span id="operators" class="bookmark"></span>
<b class="header">Operators and Aliases</b>
Because the <tt>==</tt> operator frequently causes undesirable coercion,
is intransitive, and has a different meaning than in other languages,
CoffeeScript compiles <tt>==</tt> into <tt>===</tt>, and <tt>!=</tt> into
<tt>!==</tt>.
In addition, <tt>is</tt> compiles into <tt>===</tt>,
and <tt>isnt</tt> into <tt>!==</tt>.
</p>
<p>
You can use <tt>not</tt> as an alias for <tt>!</tt>.
</p>
<p>
For logic, <tt>and</tt> compiles to <tt>&amp;&amp;</tt>, and <tt>or</tt>
into <tt>||</tt>.
</p>
<p>
Instead of a newline or semicolon, <tt>then</tt> can be used to separate
conditions from expressions, in <b>while</b>,
<b>if</b>/<b>else</b>, and <b>switch</b>/<b>when</b> statements.
</p>
<p>
As in <a href="http://yaml.org/">YAML</a>, <tt>on</tt> and <tt>yes</tt>
are the same as boolean <tt>true</tt>, while <tt>off</tt> and <tt>no</tt> are boolean <tt>false</tt>.
</p>
<p>
<tt>unless</tt> can be used as the inverse of <tt>if</tt>.
</p>
<p>
As a shortcut for <tt>this.property</tt>, you can use <tt>@property</tt>.
</p>
<p>
You can use <tt>in</tt> to test for array presence, and <tt>of</tt> to
test for JavaScript object-key presence.
</p>
<p>
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><i><small>no JS equivalent</small></i></td></tr>
</table>
<div class='code'><pre class="idle">launch() if ignition is on
volume = 10 if band isnt SpinalTap
letTheWildRumpusBegin() unless answer is no
if car.speed &lt; limit then accelerate()
winner = yes if pick in [47, 92, 13]
print inspect &quot;My name is #{@name}&quot;
</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><script>window.example29 = "launch() if ignition is on\n\nvolume = 10 if band isnt SpinalTap\n\nletTheWildRumpusBegin() unless answer is no\n\nif car.speed < limit then accelerate()\n\nwinner = yes if pick in [47, 92, 13]\n\nprint inspect \"My name is #{@name}\"\n"</script><div class='minibutton load' onclick='javascript: loadConsole(example29);'>load</div><br class='clear' /></div>
<p>
<b class="header">The Existential Operator</b>
It's a little difficult to check for the existence of a variable in
JavaScript. <tt>if (variable) ...</tt> comes close, but fails for zero,
the empty string, and false. CoffeeScript's existential operator <tt>?</tt> returns true unless
a variable is <b>null</b> or <b>undefined</b>, which makes it analogous
to Ruby's <tt>nil?</tt>
</p>
<p>
It can also be used for safer conditional assignment than <tt>||=</tt>
provides, for cases where you may be handling numbers or strings.
</p>
<div class='code'><pre class="idle">solipsism = true if mind? and not world?
speed ?= 75
footprints = yeti ? &quot;bear&quot;
</pre><pre class="idle"><span class="Storage">var</span> footprints, 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">if</span> (<span class="Keyword">typeof</span> speed <span class="Keyword">===</span> <span class="String"><span class="String">&quot;</span>undefined<span class="String">&quot;</span></span> <span class="Keyword">||</span> speed <span class="Keyword">===</span> <span class="BuiltInConstant">null</span>) speed <span class="Keyword">=</span> <span class="Number">75</span>;
footprints <span class="Keyword">=</span> <span class="Keyword">typeof</span> yeti <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> yeti <span class="Keyword">!</span><span class="Keyword">==</span> <span class="BuiltInConstant">null</span> ? yeti : <span class="String"><span class="String">&quot;</span>bear<span class="String">&quot;</span></span>;
</pre><script>window.example30 = "solipsism = true if mind? and not world?\n\nspeed ?= 75\n\nfootprints = yeti ? \"bear\"\n\nalert footprints"</script><div class='minibutton load' onclick='javascript: loadConsole(example30);'>load</div><div class='minibutton ok' onclick='javascript: var footprints, solipsism;
if ((typeof mind !== "undefined" && mind !== null) && !(typeof world !== "undefined" && world !== null)) {
solipsism = true;
}
if (typeof speed === "undefined" || speed === null) speed = 75;
footprints = typeof yeti !== "undefined" && yeti !== null ? yeti : "bear";
;alert(footprints);'>run: footprints</div><br class='clear' /></div>
<p>
The accessor variant of the existential operator <tt>?.</tt> can be used to soak
up null references in a chain of properties. Use it instead
of the dot accessor <tt>.</tt> in cases where the base value may be <b>null</b>
or <b>undefined</b>. If all of the properties exist then you'll get the expected
result, if the chain is broken, <b>undefined</b> is returned instead of
the <b>TypeError</b> that would be raised otherwise.
</p>
<div class='code'><pre class="idle">zip = lottery.drawWinner?().address?.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><script>window.example31 = "zip = lottery.drawWinner?().address?.zipcode\n"</script><div class='minibutton load' onclick='javascript: loadConsole(example31);'>load</div><br class='clear' /></div>
<p>
Soaking up nulls is similar to Ruby's
<a href="http://andand.rubyforge.org/">andand gem</a>, and to the
<a href="http://groovy.codehaus.org/Operators#Operators-SafeNavigationOperator%28%3F.%29">safe navigation operator</a>
in Groovy.
</p>
<p>
<span id="classes" class="bookmark"></span>
<b class="header">Classes, Inheritance, and Super</b>
JavaScript's prototypal inheritance has always been a bit of a
brain-bender, with a whole family tree of libraries that provide a cleaner
syntax for classical inheritance on top of JavaScript's prototypes:
<a href="http://code.google.com/p/base2/">Base2</a>,
<a href="http://prototypejs.org/">Prototype.js</a>,
<a href="http://jsclass.jcoglan.com/">JS.Class</a>, etc.
The libraries provide syntactic sugar, but the built-in inheritance would
be completely usable if it weren't for a couple of small exceptions:
it's awkward to call <b>super</b> (the prototype object's
implementation of the current function), and it's awkward to correctly
set the prototype chain.
</p>
<p>
Instead of repetitively attaching functions to a prototype, CoffeeScript
provides a basic <tt>class</tt> structure that allows you to name your class,
set the superclass, assign prototypal properties, and define the constructor,
in a single assignable expression.
</p>
<p>
Constructor functions are named, to better support helpful stack traces.
In the first class in the example below, <tt>this.constructor.name is "Animal"</tt>.
</p>
<div class='code'><pre class="idle">class Animal
constructor: (@name) -&gt;
move: (meters) -&gt;
alert @name + &quot; moved #{meters}m.&quot;
class Snake extends Animal
move: -&gt;
alert &quot;Slithering...&quot;
super 5
class Horse extends Animal
move: -&gt;
alert &quot;Galloping...&quot;
super 45
sam = new Snake &quot;Sammy the Python&quot;
tom = new Horse &quot;Tommy the Palomino&quot;
sam.move()
tom.move()
</pre><pre class="idle"><span class="Storage">var</span> Animal, Horse, Snake, sam, tom,
__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; };
Animal <span class="Keyword">=</span> (<span class="Storage">function</span>() {
Animal.<span class="LibraryConstant">name</span> <span class="Keyword">=</span> <span class="String"><span class="String">'</span>Animal<span class="String">'</span></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;
})();
Snake <span class="Keyword">=</span> (<span class="Storage">function</span>(_super) {
__extends(Snake, _super);
Snake.<span class="LibraryConstant">name</span> <span class="Keyword">=</span> <span class="String"><span class="String">'</span>Snake<span class="String">'</span></span>;
<span class="Storage">function</span> <span class="FunctionName">Snake</span>() {
<span class="Keyword">return</span> Snake.__super__.<span class="LibraryConstant">constructor</span>.<span class="LibraryFunction">apply</span>(<span class="Variable">this</span>, arguments);
}
<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;
})(Animal);
Horse <span class="Keyword">=</span> (<span class="Storage">function</span>(_super) {
__extends(Horse, _super);
Horse.<span class="LibraryConstant">name</span> <span class="Keyword">=</span> <span class="String"><span class="String">'</span>Horse<span class="String">'</span></span>;
<span class="Storage">function</span> <span class="FunctionName">Horse</span>() {
<span class="Keyword">return</span> Horse.__super__.<span class="LibraryConstant">constructor</span>.<span class="LibraryFunction">apply</span>(<span class="Variable">this</span>, arguments);
}
<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;
})(Animal);
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><script>window.example32 = "class Animal\n constructor: (@name) ->\n\n move: (meters) ->\n alert @name + \" moved #{meters}m.\"\n\nclass Snake extends Animal\n move: ->\n alert \"Slithering...\"\n super 5\n\nclass Horse extends Animal\n move: ->\n alert \"Galloping...\"\n super 45\n\nsam = new Snake \"Sammy the Python\"\ntom = new Horse \"Tommy the Palomino\"\n\nsam.move()\ntom.move()\n\n\n\n\n"</script><div class='minibutton load' onclick='javascript: loadConsole(example32);'>load</div><div class='minibutton ok' onclick='javascript: var Animal, Horse, Snake, sam, tom,
__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() {
Animal.name = 'Animal';
function Animal(name) {
this.name = name;
}
Animal.prototype.move = function(meters) {
return alert(this.name + (" moved " + meters + "m."));
};
return Animal;
})();
Snake = (function(_super) {
__extends(Snake, _super);
Snake.name = 'Snake';
function Snake() {
return Snake.__super__.constructor.apply(this, arguments);
}
Snake.prototype.move = function() {
alert("Slithering...");
return Snake.__super__.move.call(this, 5);
};
return Snake;
})(Animal);
Horse = (function(_super) {
__extends(Horse, _super);
Horse.name = 'Horse';
function Horse() {
return Horse.__super__.constructor.apply(this, arguments);
}
Horse.prototype.move = function() {
alert("Galloping...");
return Horse.__super__.move.call(this, 45);
};
return Horse;
})(Animal);
sam = new Snake("Sammy the Python");
tom = new Horse("Tommy the Palomino");
sam.move();
tom.move();
;'>run</div><br class='clear' /></div>
<p>
If structuring your prototypes classically isn't your cup of tea, CoffeeScript
provides a couple of lower-level conveniences. The <tt>extends</tt> operator
helps with proper prototype setup, and can be used to create an inheritance
chain between any pair of constructor functions; <tt>::</tt> gives you
quick access to an object's prototype; and <tt>super()</tt>
is converted into a call against the immediate ancestor's method of the same name.
</p>
<div class='code'><pre class="idle">String::dasherize = -&gt;
this.replace /_/g, &quot;-&quot;
</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><script>window.example33 = "String::dasherize = ->\n this.replace /_/g, \"-\"\n\nalert \"one_two\".dasherize()"</script><div class='minibutton load' onclick='javascript: loadConsole(example33);'>load</div><div class='minibutton ok' onclick='javascript:
String.prototype.dasherize = function() {
return this.replace(/_/g, "-");
};
;alert("one_two".dasherize());'>run: "one_two".dasherize()</div><br class='clear' /></div>
<p>
Finally, class definitions are blocks of executable code, which make for interesting
metaprogramming possibilities. Because in the context of a class definition,
<tt>this</tt> is the class object itself (the constructor function), you
can assign static properties by using <br /><tt>@property: value</tt>, and call
functions defined in parent classes: <tt>@attr 'title', type: 'text'</tt>
</p>
<p>
<span id="destructuring" class="bookmark"></span>
<b class="header">Destructuring Assignment</b>
To make extracting values from complex arrays and objects more convenient,
CoffeeScript implements ECMAScript Harmony's proposed
<a href="http://wiki.ecmascript.org/doku.php?id=harmony:destructuring">destructuring assignment</a>
syntax. When you assign an array or object literal to a value, CoffeeScript
breaks up and matches both sides against each other, assigning the values
on the right to the variables on the left. In the simplest case, it can be
used for parallel assignment:
</p>
<div class='code'><pre class="idle">theBait = 1000
theSwitch = 0
[theBait, theSwitch] = [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><script>window.example34 = "theBait = 1000\ntheSwitch = 0\n\n[theBait, theSwitch] = [theSwitch, theBait]\n\nalert theBait"</script><div class='minibutton load' onclick='javascript: loadConsole(example34);'>load</div><div class='minibutton ok' onclick='javascript: var theBait, theSwitch, _ref;
theBait = 1000;
theSwitch = 0;
_ref = [theSwitch, theBait], theBait = _ref[0], theSwitch = _ref[1];
;alert(theBait);'>run: theBait</div><br class='clear' /></div>
<p>
But it's also helpful for dealing with functions that return multiple
values.
</p>
<div class='code'><pre class="idle">weatherReport = (location) -&gt;
# Make an Ajax request to fetch the weather...
[location, 72, &quot;Mostly Sunny&quot;]
[city, temp, forecast] = weatherReport &quot;Berkeley, CA&quot;
</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><script>window.example35 = "weatherReport = (location) ->\n # Make an Ajax request to fetch the weather...\n [location, 72, \"Mostly Sunny\"]\n\n[city, temp, forecast] = weatherReport \"Berkeley, CA\"\n\nalert forecast"</script><div class='minibutton load' onclick='javascript: loadConsole(example35);'>load</div><div class='minibutton ok' onclick='javascript: var city, forecast, temp, weatherReport, _ref;
weatherReport = function(location) {
return [location, 72, "Mostly Sunny"];
};
_ref = weatherReport("Berkeley, CA"), city = _ref[0], temp = _ref[1], forecast = _ref[2];
;alert(forecast);'>run: forecast</div><br class='clear' /></div>
<p>
Destructuring assignment can be used with any depth of array and object nesting,
to help pull out deeply nested properties.
</p>
<div class='code'><pre class="idle">futurists =
sculptor: &quot;Umberto Boccioni&quot;
painter: &quot;Vladimir Burliuk&quot;
poet:
name: &quot;F.T. Marinetti&quot;
address: [
&quot;Via Roma 42R&quot;
&quot;Bellagio, Italy 22021&quot;
]
{poet: {name, address: [street, city]}} = 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><script>window.example36 = "futurists =\n sculptor: \"Umberto Boccioni\"\n painter: \"Vladimir Burliuk\"\n poet:\n name: \"F.T. Marinetti\"\n address: [\n \"Via Roma 42R\"\n \"Bellagio, Italy 22021\"\n ]\n\n{poet: {name, address: [street, city]}} = futurists\n\nalert name + \" - \" + street"</script><div class='minibutton load' onclick='javascript: loadConsole(example36);'>load</div><div class='minibutton ok' 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</div><br class='clear' /></div>
<p>
Destructuring assignment can even be combined with splats.
</p>
<div class='code'><pre class="idle">tag = &quot;&lt;impossible&gt;&quot;
[open, contents..., close] = tag.split(&quot;&quot;)
</pre><pre class="idle"><span class="Storage">var</span> close, contents, open, tag, _i, _ref,
__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><script>window.example37 = "tag = \"<impossible>\"\n\n[open, contents..., close] = tag.split(\"\")\n\nalert contents.join(\"\")"</script><div class='minibutton load' onclick='javascript: loadConsole(example37);'>load</div><div class='minibutton ok' onclick='javascript: var close, contents, open, tag, _i, _ref,
__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("")</div><br class='clear' /></div>
<p>
<span id="fat_arrow" class="bookmark"></span>
<b class="header">Function binding</b>
In JavaScript, the <tt>this</tt> keyword is dynamically scoped to mean the
object that the current function is attached to. If you pass a function as
a callback or attach it to a different object, the original value of <tt>this</tt>
will be lost. If you're not familiar with this behavior,
<a href="http://www.digital-web.com/articles/scope_in_javascript/">this Digital Web article</a>
gives a good overview of the quirks.
</p>
<p>
The fat arrow <tt>=&gt;</tt> can be used to both define a function, and to bind
it to the current value of <tt>this</tt>, right on the spot. This is helpful
when using callback-based libraries like Prototype or jQuery, for creating
iterator functions to pass to <tt>each</tt>, or event-handler functions
to use with <tt>bind</tt>. Functions created with the fat arrow are able to access
properties of the <tt>this</tt> where they're defined.
</p>
<div class='code'><pre class="idle">Account = (customer, cart) -&gt;
@customer = customer
@cart = cart
$('.shopping_cart').bind 'click', (event) =&gt;
@customer.purchase @cart
</pre><pre class="idle"><span class="Storage">var</span> Account;
<span class="FunctionName">Account</span> = <span class="Storage">function</span>(<span class="FunctionArgument">customer, cart</span>) {
<span class="Storage">var</span> _this <span class="Keyword">=</span> <span class="Variable">this</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>, <span class="Storage">function</span>(<span class="LibraryClassType">event</span>) {
<span class="Keyword">return</span> _this.customer.purchase(_this.cart);
});
};
</pre><script>window.example38 = "Account = (customer, cart) ->\n @customer = customer\n @cart = cart\n\n $('.shopping_cart').bind 'click', (event) =>\n @customer.purchase @cart"</script><div class='minibutton load' onclick='javascript: loadConsole(example38);'>load</div><br class='clear' /></div>
<p>
If we had used <tt>-&gt;</tt> in the callback above, <tt>@customer</tt> would
have referred to the undefined "customer" property of the DOM element,
and trying to call <tt>purchase()</tt> on it would have raised an exception.
</p>
<p>
When used in a class definition, methods declared with the fat arrow will
be automatically bound to each instance of the class when the instance is
constructed.
</p>
<p>
<span id="embedded" class="bookmark"></span>
<b class="header">Embedded JavaScript</b>
Hopefully, you'll never need to use it, but if you ever need to intersperse
snippets of JavaScript within your CoffeeScript, you can
use backticks to pass it straight through.
</p>
<div class='code'><pre class="idle">hi = `function() {
return [document.title, &quot;Hello JavaScript&quot;].join(&quot;: &quot;);
}`
</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><script>window.example39 = "hi = `function() {\n return [document.title, \"Hello JavaScript\"].join(\": \");\n}`\n\nalert hi()"</script><div class='minibutton load' onclick='javascript: loadConsole(example39);'>load</div><div class='minibutton ok' onclick='javascript: var hi;
hi = function() {
return [document.title, "Hello JavaScript"].join(": ");
};
;alert(hi());'>run: hi()</div><br class='clear' /></div>
<p>
<span id="switch" class="bookmark"></span>
<b class="header">Switch/When/Else</b>
<b>Switch</b> statements in JavaScript are a bit awkward. You need to
remember to <b>break</b> at the end of every <b>case</b> statement to
avoid accidentally falling through to the default case.
CoffeeScript prevents accidental fall-through, and can convert the <tt>switch</tt>
into a returnable, assignable expression. The format is: <tt>switch</tt> condition,