coffeescript
Version:
Unfancy JavaScript
885 lines (823 loc) • 133 kB
HTML
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=UTF-8" />
<title>CoffeeScript</title>
<link rel="stylesheet" type="text/css" href="documentation/css/docs.css" />
<link rel="stylesheet" type="text/css" href="documentation/css/idle.css" />
<link rel="shortcut icon" href="documentation/images/favicon.ico" />
</head>
<body class="minimized">
<div id="fadeout"></div>
<div id="flybar">
<a id="logo" href="#top"> </a>
<div class="navigation toc">
<div class="button">
Table of Contents
</div>
<div class="contents">
<a href="#overview">Mini Overview</a>
<a href="#installation">Installation and Usage</a>
<a href="#language">Language Reference</a>
<a href="#whitespace">Significant Whitespace</a>
<a href="#functions">Functions and Invocation</a>
<a href="#objects_and_arrays">Objects and Arrays</a>
<a href="#lexical_scope">Lexical Scoping and Variable Safety</a>
<a href="#conditionals">If, Else, Unless, and Conditional Assignment</a>
<a href="#aliases">Aliases</a>
<a href="#splats">Splats...</a>
<a href="#while">While, Until, and Loop</a>
<a href="#comprehensions">Comprehensions (Arrays, Objects, and Ranges)</a>
<a href="#slice_splice">Array Slicing and Splicing with Ranges</a>
<a href="#expressions">Everything is an Expression</a>
<a href="#existence">The Existential Operator</a>
<a href="#classes">Classes, Inheritance, and Super</a>
<a href="#pattern_matching">Pattern Matching</a>
<a href="#fat_arrow">Function Binding</a>
<a href="#embedded">Embedded JavaScript</a>
<a href="#switch">Switch/When/Else</a>
<a href="#try">Try/Catch/Finally</a>
<a href="#comparisons">Chained Comparisons</a>
<a href="#interpolation">String and RegExp Interpolation</a>
<a href="#heredocs">Multiline Strings, Heredocs, and Block Comments</a>
<a href="#cake">Cake, and Cakefiles</a>
<a href="#scripts">"text/coffeescript" Script Tags</a>
<a href="#resources">Resources</a>
<a href="#webchat">Web Chat (IRC)</a>
<a href="#change_log">Change Log</a>
</div>
</div>
<div class="navigation try">
<div class="button">
Try CoffeeScript
</div>
<div class="contents repl_wrapper">
<div class="code">
<div id="repl_source_wrap"><textarea id="repl_source">reverse = (string) ->
string.split('').reverse().join ''
alert reverse '.eeffoC yrT'</textarea></div>
<pre id="repl_results"></pre>
<button class="full_screen">go full screen</button>
<button class="minimize">minimize</button>
<button class="run">run</button>
<br class="clear" />
</div>
</div>
</div>
<div class="navigation annotated">
<div class="button">
Annotated Source
</div>
<div class="contents">
<a href="documentation/docs/grammar.html">Grammar Rules — src/grammar</a>
<a href="documentation/docs/lexer.html">Lexing Tokens — src/lexer</a>
<a href="documentation/docs/rewriter.html">The Rewriter — src/rewriter</a>
<a href="documentation/docs/nodes.html">The Syntax Tree — src/nodes</a>
<a href="documentation/docs/scope.html">Lexical Scope — src/scope</a>
<a href="documentation/docs/helpers.html">Helpers & Utility Functions — src/helpers</a>
<a href="documentation/docs/coffee-script.html">The CoffeeScript Module — src/coffee-script</a>
<a href="documentation/docs/cake.html">Cake & Cakefiles — src/cake</a>
<a href="documentation/docs/command.html">"coffee" Command-Line Utility — src/command</a>
<a href="documentation/docs/optparse.html">Option Parsing — src/optparse</a>
<a href="documentation/docs/repl.html">Interactive REPL — 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. Think
of it as JavaScript's less ostentatious kid brother — the same genes,
roughly the same height, but a different sense of style. Apart from a handful of
bonus goodies, statements in CoffeeScript correspond one-to-one with their
equivalent in JavaScript, it's just another way of saying it.
</p>
<p>
<b>Disclaimer:</b>
CoffeeScript is just for fun. Until it reaches 1.0, <i>there are no guarantees
that the syntax won't change between versions.</i> That said,
it compiles into clean JavaScript (the good parts) that can use existing
JavaScript libraries seamlessly, and passes through
<a href="http://www.jslint.com/">JSLint</a> without warnings. The compiled
output is pretty-printed and quite readable.
</p>
<p>
<b>Latest Version:</b>
<a href="http://github.com/jashkenas/coffee-script/tarball/0.9.0">0.9.0</a>
</p>
<h2>
<span id="overview" class="bookmark"></span>
Mini Overview
</h2>
<p><i>CoffeeScript on the left, compiled JavaScript output on the right.</i></p>
<div class='code'><pre class="idle"><span class="Comment"><span class="Comment">#</span> Assignment:</span>
number <span class="Keyword">=</span> <span class="Number">42</span>
opposite <span class="Keyword">=</span> <span class="BuiltInConstant">true</span>
<span class="Comment"><span class="Comment">#</span> Conditions:</span>
number <span class="Keyword">=</span> <span class="Keyword">-</span><span class="Number">42</span> <span class="Keyword">if</span> opposite
<span class="Comment"><span class="Comment">#</span> Functions:</span>
<span class="FunctionName">square </span><span class="Keyword">=</span> <span class="FunctionArgument">(</span><span class="FunctionArgument">x</span><span class="FunctionArgument">)</span> <span class="Storage">-></span> x <span class="Keyword">*</span> x
<span class="Comment"><span class="Comment">#</span> Arrays:</span>
list <span class="Keyword">=</span> [<span class="Number">1</span>, <span class="Number">2</span>, <span class="Number">3</span>, <span class="Number">4</span>, <span class="Number">5</span>]
<span class="Comment"><span class="Comment">#</span> Objects:</span>
math <span class="Keyword">=</span>
root<span class="Keyword">:</span> Math.sqrt
square<span class="Keyword">:</span> square
<span class="FunctionName">cube</span><span class="Keyword">:</span> <span class="FunctionArgument">(</span><span class="FunctionArgument">x</span><span class="FunctionArgument">)</span> <span class="Storage">-></span> x <span class="Keyword">*</span> square x
<span class="Comment"><span class="Comment">#</span> Splats:</span>
<span class="FunctionName">race </span><span class="Keyword">=</span> <span class="FunctionArgument">(</span><span class="FunctionArgument">winner, runners...</span><span class="FunctionArgument">)</span> <span class="Storage">-></span>
print winner, runners
<span class="Comment"><span class="Comment">#</span> Existence:</span>
alert <span class="String"><span class="String">"</span>I knew it!<span class="String">"</span></span> <span class="Keyword">if</span> elvis<span class="Keyword">?</span>
<span class="Comment"><span class="Comment">#</span> Array comprehensions:</span>
cubes <span class="Keyword">=</span> math.cube num <span class="Keyword">for</span> num <span class="Keyword">in</span> list
</pre><pre class="idle"><span class="Storage">var</span> _a, _b, _c, _d, cubes, list, math, num, number, opposite, race, square;
<span class="Storage">var</span> __slice <span class="Keyword">=</span> <span class="LibraryClassType">Array</span>.<span class="LibraryConstant">prototype</span>.slice;
number <span class="Keyword">=</span> <span class="Number">42</span>;
opposite <span class="Keyword">=</span> <span class="BuiltInConstant">true</span>;
<span class="Keyword">if</span> (opposite) {
number <span class="Keyword">=</span> <span class="Keyword">-</span><span class="Number">42</span>;
}
<span class="FunctionName">square</span> = <span class="Storage">function</span>(<span class="FunctionArgument">x</span>) {
<span class="Keyword">return</span> x <span class="Keyword">*</span> x;
};
list <span class="Keyword">=</span> [<span class="Number">1</span>, <span class="Number">2</span>, <span class="Number">3</span>, <span class="Number">4</span>, <span class="Number">5</span>];
math <span class="Keyword">=</span> {
root: <span class="LibraryClassType">Math</span>.sqrt,
square: square,
<span class="FunctionName">cube</span>: <span class="Storage">function</span>(<span class="FunctionArgument">x</span>) {
<span class="Keyword">return</span> x <span class="Keyword">*</span> square(x);
}
};
<span class="FunctionName">race</span> = <span class="Storage">function</span>(<span class="FunctionArgument">winner</span>) {
<span class="Storage">var</span> runners;
runners <span class="Keyword">=</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">"</span>undefined<span class="String">"</span></span> <span class="Keyword">&</span><span class="Keyword">&</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">"</span>I knew it!<span class="String">"</span></span>);
}
cubes <span class="Keyword">=</span> (<span class="Storage">function</span>() {
_a <span class="Keyword">=</span> []; _c <span class="Keyword">=</span> list;
<span class="Keyword">for</span> (_b <span class="Keyword">=</span> <span class="Number">0</span>, _d <span class="Keyword">=</span> _c.<span class="LibraryConstant">length</span>; _b <span class="Keyword"><</span> _d; _b<span class="Keyword">++</span>) {
num <span class="Keyword">=</span> _c[_b];
_a.<span class="LibraryFunction">push</span>(math.cube(num));
}
<span class="Keyword">return</span> _a;
})();
</pre><button onclick='javascript: var _a, _b, _c, _d, cubes, list, math, num, number, opposite, race, square;
var __slice = Array.prototype.slice;
number = 42;
opposite = true;
if (opposite) {
number = -42;
}
square = function(x) {
return x * x;
};
list = [1, 2, 3, 4, 5];
math = {
root: Math.sqrt,
square: square,
cube: function(x) {
return x * square(x);
}
};
race = function(winner) {
var runners;
runners = __slice.call(arguments, 1);
return print(winner, runners);
};
if (typeof elvis !== "undefined" && elvis !== null) {
alert("I knew it!");
}
cubes = (function() {
_a = []; _c = list;
for (_b = 0, _d = _c.length; _b < _d; _b++) {
num = _c[_b];
_a.push(math.cube(num));
}
return _a;
})();;alert(cubes);'>run: cubes</button><br class='clear' /></div>
<p>
For a longer CoffeeScript example, check out
<a href="documentation/docs/underscore.html">Underscore.coffee</a>, a port
of the <a href="http://documentcloud.github.com/underscore/">Underscore.js</a>
library of helper functions. Underscore.coffee can pass the entire Underscore.js
test suite. The CoffeeScript version is faster than the original for a number
of methods (in general, due to the speed of CoffeeScript's array comprehensions), and
after being minified and gzipped, is only 241 bytes larger than the original
JavaScript version.
Additional examples are included in the source repository, inside the
<a href="http://github.com/jashkenas/coffee-script/tree/master/examples/">examples</a> folder.
</p>
<h2>
<span id="installation" class="bookmark"></span>
Installation and Usage
</h2>
<p>
The CoffeeScript compiler is written in pure CoffeeScript, using a
<a href="documentation/docs/grammar.html">small DSL</a>
on top of the <a href="http://github.com/zaach/jison">Jison parser generator</a>, and is available
as a <a href="http://nodejs.org/">Node.js</a> utility. The core compiler however,
does not depend on Node, and can be run in other server-side-JavaScript environments,
or in the browser (see "Try CoffeeScript", above).
</p>
<p>
To install, first make sure you have a working copy of the latest tagged version of
<a href="http://nodejs.org/">Node.js</a>, currently <b>0.1.102</b> or higher.
Then clone the CoffeeScript
<a href="http://github.com/jashkenas/coffee-script">source repository</a>
from GitHub, or download the latest
release: <a href="http://github.com/jashkenas/coffee-script/tarball/0.9.0">0.9.0</a>.
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>
Alternatively, if you already have the
<a href="http://npmjs.org/">Node Package Manager</a> installed,
you can use that to grab the latest CoffeeScript:
</p>
<pre>
sudo npm install coffee-script</pre>
<p>
Both of these provide the <tt>coffee</tt> command, which will execute CoffeeScripts
under Node.js by default, but is also used to compile CoffeeScript
<tt>.coffee</tt> files into JavaScript, or to run an an interactive REPL.
When compiling to JavaScript, <tt>coffee</tt> writes the output
as <tt>.js</tt> files in the same directory by default, but output
can be customized with the following options:
</p>
<table>
<tr>
<td><code>-c, --compile</code></td>
<td>
Compile a <tt>.coffee</tt> script into a <tt>.js</tt> JavaScript file
of the same name.
</td>
</tr>
<tr>
<td width="25%"><code>-i, --interactive</code></td>
<td>
Launch an interactive CoffeeScript session to try short snippets.
More pleasant if wrapped with
<a href="http://utopia.knoware.nl/~hlub/uck/rlwrap/rlwrap.html">rlwrap</a>.
</td>
</tr>
<tr>
<td><code>-o, --output [DIR]</code></td>
<td>
Write out all compiled JavaScript files into the specified directory.
Use in conjunction with <tt>--compile</tt> or <tt>--watch</tt>.
</td>
</tr>
<tr>
<td><code>-w, --watch</code></td>
<td>
Watch the modification times of the coffee-scripts, recompiling as
soon as a change occurs.
</td>
</tr>
<tr>
<td><code>-p, --print</code></td>
<td>
Instead of writing out the JavaScript as a file, print it
directly to <b>stdout</b>.
</td>
</tr>
<tr>
<td><code>-l, --lint</code></td>
<td>
If the <tt>jsl</tt>
(<a href="http://www.javascriptlint.com/">JavaScript Lint</a>)
command is installed, use it
to check the compilation of a CoffeeScript file. (Handy in
conjunction with <br /> <tt>--watch</tt>)
</td>
</tr>
<tr>
<td><code>-s, --stdio</code></td>
<td>
Pipe in CoffeeScript to STDIN and get back JavaScript over STDOUT.
Good for use with processes written in other languages. An example:<br />
<tt>cat src/cake.coffee | coffee -sc</tt>
</td>
</tr>
<tr>
<td><code>-e, --eval</code></td>
<td>
Compile and print a little snippet of CoffeeScript directly from the
command line. For example:<br /><tt>coffee -e "puts num for num in [10..1]"</tt>
</td>
</tr>
<tr>
<td><code>--no-wrap</code></td>
<td>
Compile the JavaScript without the top-level function safety wrapper.
(Used for CoffeeScript as a Node.js module.)
</td>
</tr>
<tr>
<td><code>-t, --tokens</code></td>
<td>
Instead of parsing the CoffeeScript, just lex it, and print out the
token stream: <tt>[IDENTIFIER square] [ASSIGN =] [PARAM_START (]</tt> ...
</td>
</tr>
<tr>
<td><code>-n, --nodes</code></td>
<td>
Instead of compiling the CoffeeScript, just lex and parse it, and print
out the parse tree:
<pre class="no_bar">
Expressions
Assign
Value "square"
Code "x"
Op *
Value "x"
Value "x"</pre>
</td>
</tr>
</table>
<p>
<b>Examples:</b>
</p>
<pre>
coffee -c path/to/script.coffee
coffee --interactive
coffee --watch --lint experimental.coffee
coffee --print app/scripts/*.coffee > concatenation.js</pre>
<h2>
<span id="language" class="bookmark"></span>
Language Reference
</h2>
<p>
<i>
This reference is structured so that it can be read from top to bottom,
if you like. Later sections use ideas and syntax previously introduced.
Familiarity with JavaScript is assumed.
In all of the following examples, the source CoffeeScript is provided on
the left, and the direct compilation into JavaScript is on the right.
</i>
</p>
<p>
<i>
Many of the examples can be run (where it makes sense) by pressing the "run"
button towards the bottom right. You can also paste examples into
"Try CoffeeScript" in the toolbar, and play with them from there.
</i>
<p>
<span id="whitespace" class="bookmark"></span>
<b class="header">Significant Whitespace</b>
CoffeeScript uses Python-style significant whitespace: You don't need to
use semicolons <tt>;</tt> to terminate expressions, ending
the line will do just as well. Semicolons can still be used to fit
multiple expressions onto a single line. Instead of using curly braces
<tt>{ }</tt> to delimit blocks of code (like <a href="#functions">functions</a>,
<a href="#conditionals">if-statements</a>,
<a href="#switch">switch</a>, and <a href="#try">try/catch</a>),
use indentation.
</p>
<p>
You don't need to use parentheses to invoke a function if you're passing
arguments:<br /><tt>print "coffee"</tt>. Implicit parentheses wrap forwards
to the end of the line, or block expression.
</p>
<p>
You can use newlines to break up your expression into smaller pieces,
as long as CoffeeScript can determine that the line hasn't finished yet,
because it ends with an operator or a dot ... seen most commonly
in jQuery-chaining style JavaScript.
</p>
<p>
<span id="functions" class="bookmark"></span>
<b class="header">Functions and Invocation</b>
Functions are defined by a list of parameters, an arrow, and the
function body. The empty function looks like this: <tt>-></tt>
</p>
<div class='code'><pre class="idle"><span class="FunctionName">square </span><span class="Keyword">=</span> <span class="FunctionArgument">(</span><span class="FunctionArgument">x</span><span class="FunctionArgument">)</span> <span class="Storage">-></span> x <span class="Keyword">*</span> x
<span class="FunctionName">cube </span><span class="Keyword">=</span> <span class="FunctionArgument">(</span><span class="FunctionArgument">x</span><span class="FunctionArgument">)</span> <span class="Storage">-></span> square(x) <span class="Keyword">*</span> x
</pre><pre class="idle"><span class="Storage">var</span> cube, square;
<span class="FunctionName">square</span> = <span class="Storage">function</span>(<span class="FunctionArgument">x</span>) {
<span class="Keyword">return</span> x <span class="Keyword">*</span> x;
};
<span class="FunctionName">cube</span> = <span class="Storage">function</span>(<span class="FunctionArgument">x</span>) {
<span class="Keyword">return</span> square(x) <span class="Keyword">*</span> x;
};
</pre><button onclick='javascript: var cube, square;
square = function(x) {
return x * x;
};
cube = function(x) {
return square(x) * x;
};;alert(cube(5));'>run: cube(5)</button><br class='clear' /></div>
<p>
<span id="objects_and_arrays" class="bookmark"></span>
<b class="header">Objects and Arrays</b>
Object and Array literals look very similar to their JavaScript cousins.
When you spread out each property on a separate line, the commas are
optional. Implicit objects may be created with indentation instead of
brackets, winding up looking quite similar to YAML.
</p>
<div class='code'><pre class="idle">song <span class="Keyword">=</span> [<span class="String"><span class="String">"</span>do<span class="String">"</span></span>, <span class="String"><span class="String">"</span>re<span class="String">"</span></span>, <span class="String"><span class="String">"</span>mi<span class="String">"</span></span>, <span class="String"><span class="String">"</span>fa<span class="String">"</span></span>, <span class="String"><span class="String">"</span>so<span class="String">"</span></span>]
singers <span class="Keyword">=</span> {Jagger<span class="Keyword">:</span> <span class="String"><span class="String">"</span>Rock<span class="String">"</span></span>, Elvis<span class="Keyword">:</span> <span class="String"><span class="String">"</span>Roll<span class="String">"</span></span>}
matrix <span class="Keyword">=</span> [
<span class="Number">1</span>, <span class="Number">0</span>, <span class="Number">1</span>
<span class="Number">0</span>, <span class="Number">0</span>, <span class="Number">1</span>
<span class="Number">1</span>, <span class="Number">1</span>, <span class="Number">0</span>
]
kids <span class="Keyword">=</span>
brother<span class="Keyword">:</span>
name<span class="Keyword">:</span> <span class="String"><span class="String">"</span>Max<span class="String">"</span></span>
age<span class="Keyword">:</span> <span class="Number">11</span>
sister<span class="Keyword">:</span>
name<span class="Keyword">:</span> <span class="String"><span class="String">"</span>Ida<span class="String">"</span></span>
age<span class="Keyword">:</span> <span class="Number">9</span>
</pre><pre class="idle"><span class="Storage">var</span> kids, matrix, singers, song;
song <span class="Keyword">=</span> [<span class="String"><span class="String">"</span>do<span class="String">"</span></span>, <span class="String"><span class="String">"</span>re<span class="String">"</span></span>, <span class="String"><span class="String">"</span>mi<span class="String">"</span></span>, <span class="String"><span class="String">"</span>fa<span class="String">"</span></span>, <span class="String"><span class="String">"</span>so<span class="String">"</span></span>];
singers <span class="Keyword">=</span> {
Jagger: <span class="String"><span class="String">"</span>Rock<span class="String">"</span></span>,
Elvis: <span class="String"><span class="String">"</span>Roll<span class="String">"</span></span>
};
matrix <span class="Keyword">=</span> [<span class="Number">1</span>, <span class="Number">0</span>, <span class="Number">1</span>, <span class="Number">0</span>, <span class="Number">0</span>, <span class="Number">1</span>, <span class="Number">1</span>, <span class="Number">1</span>, <span class="Number">0</span>];
kids <span class="Keyword">=</span> {
brother: {
name: <span class="String"><span class="String">"</span>Max<span class="String">"</span></span>,
age: <span class="Number">11</span>
},
sister: {
name: <span class="String"><span class="String">"</span>Ida<span class="String">"</span></span>,
age: <span class="Number">9</span>
}
};
</pre><button onclick='javascript: var kids, matrix, singers, song;
song = ["do", "re", "mi", "fa", "so"];
singers = {
Jagger: "Rock",
Elvis: "Roll"
};
matrix = [1, 0, 1, 0, 0, 1, 1, 1, 0];
kids = {
brother: {
name: "Max",
age: 11
},
sister: {
name: "Ida",
age: 9
}
};;alert(song.join(","));'>run: song.join(",")</button><br class='clear' /></div>
<p>
In JavaScript, you can't use reserved words, like <tt>class</tt>, as properties
of an object, without quoting them as strings. CoffeeScript notices and quotes
them for you, so you don't have to worry about it (say, when using jQuery).
</p>
<div class='code'><pre class="idle">$(<span class="String"><span class="String">'</span>.account<span class="String">'</span></span>).css class<span class="Keyword">:</span> <span class="String"><span class="String">'</span>active<span class="String">'</span></span>
</pre><pre class="idle"><span class="Keyword">$</span>(<span class="String"><span class="String">'</span>.account<span class="String">'</span></span>).css({
<span class="String"><span class="String">"</span>class<span class="String">"</span></span>: <span class="String"><span class="String">'</span>active<span class="String">'</span></span>
});
</pre><br class='clear' /></div>
<p>
<span id="lexical_scope" class="bookmark"></span>
<b class="header">Lexical Scoping and Variable Safety</b>
The CoffeeScript compiler takes care to make sure that all of your variables
are properly declared within lexical scope — you never need to write
<tt>var</tt> yourself.
</p>
<div class='code'><pre class="idle">outer <span class="Keyword">=</span> <span class="Number">1</span>
<span class="FunctionName">changeNumbers </span><span class="Keyword">=</span> <span class="Storage">-></span>
inner <span class="Keyword">=</span> <span class="Keyword">-</span><span class="Number">1</span>
outer <span class="Keyword">=</span> <span class="Number">10</span>
inner <span class="Keyword">=</span> changeNumbers()
</pre><pre class="idle"><span class="Storage">var</span> changeNumbers, inner, outer;
outer <span class="Keyword">=</span> <span class="Number">1</span>;
<span class="FunctionName">changeNumbers</span> = <span class="Storage">function</span>() {
<span class="Storage">var</span> inner;
inner <span class="Keyword">=</span> <span class="Keyword">-</span><span class="Number">1</span>;
<span class="Keyword">return</span> (outer <span class="Keyword">=</span> <span class="Number">10</span>);
};
inner <span class="Keyword">=</span> changeNumbers();
</pre><button onclick='javascript: var changeNumbers, inner, outer;
outer = 1;
changeNumbers = function() {
var inner;
inner = -1;
return (outer = 10);
};
inner = changeNumbers();;alert(inner);'>run: inner</button><br class='clear' /></div>
<p>
Notice how all of the variable declarations have been pushed up to
the top of the closest scope, the first time they appear.
<b>outer</b> is not redeclared within the inner function, because it's
already in scope; <b>inner</b> within the function, on the other hand,
should not be able to change the value of the external variable of the same name, and
therefore has a declaration of its own.
</p>
<p>
This behavior is effectively identical to Ruby's scope for local variables.
Because you don't have direct access to the <tt>var</tt> keyword,
it's impossible to shadow an outer variable on purpose, you may only refer
to it. So be careful that you're not reusing the name of an external
variable accidentally, if you're writing a deeply nested function.
</p>
<p>
Although suppressed within this documentation for clarity, all
CoffeeScript output is wrapped in an anonymous function:
<tt>(function(){ ... })();</tt> This safety wrapper, combined with the
automatic generation of the <tt>var</tt> keyword, make it exceedingly difficult
to pollute the global namespace by accident.
</p>
<p>
If you'd like to create top-level variables for other scripts to use,
attach them as properties on <b>window</b>, or on the <b>exports</b>
object in CommonJS. The <b>existential operator</b> (covered below), gives you a
reliable way to figure out where to add them, if you're targeting both
CommonJS and the browser: <tt>root = 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 — you simply use
a regular <b>if</b> statement inline.
</p>
<div class='code'><pre class="idle">mood <span class="Keyword">=</span> greatlyImproved <span class="Keyword">if</span> singing
<span class="Keyword">if</span> happy <span class="Keyword">and</span> knowsIt
clapsHands()
chaChaCha()
<span class="Keyword">else</span>
showIt()
date <span class="Keyword">=</span> <span class="Keyword">if</span> friday <span class="Keyword">then</span> sue <span class="Keyword">else</span> jill
options or<span class="Keyword">=</span> defaults
</pre><pre class="idle"><span class="Storage">var</span> date, mood, options;
<span class="Keyword">if</span> (singing) {
mood <span class="Keyword">=</span> greatlyImproved;
}
<span class="Keyword">if</span> (happy <span class="Keyword">&</span><span class="Keyword">&</span> knowsIt) {
clapsHands();
chaChaCha();
} <span class="Keyword">else</span> {
showIt();
}
date <span class="Keyword">=</span> friday ? sue : jill;
options <span class="Keyword">=</span> options <span class="Keyword">||</span> defaults;
</pre><br class='clear' /></div>
<p>
<span id="aliases" class="bookmark"></span>
<b class="header">Aliases</b>
Because the <tt>==</tt> operator frequently causes undesirable coercion,
is intransitive, and has a different meaning than in other languages,
CoffeeScript compiles <tt>==</tt> into <tt>===</tt>, and <tt>!=</tt> into
<tt>!==</tt>.
In addition, <tt>is</tt> compiles into <tt>===</tt>,
and <tt>isnt</tt> into <tt>!==</tt>.
</p>
<p>
You can use <tt>not</tt> as an alias for <tt>!</tt>.
</p>
<p>
For logic, <tt>and</tt> compiles to <tt>&&</tt>, and <tt>or</tt>
into <tt>||</tt>.
</p>
<p>
Instead of a newline or semicolon, <tt>then</tt> can be used to separate
conditions from expressions, in <b>while</b>,
<b>if</b>/<b>else</b>, and <b>switch</b>/<b>when</b> statements.
</p>
<p>
As in <a href="http://yaml.org/">YAML</a>, <tt>on</tt> and <tt>yes</tt>
are the same as boolean <tt>true</tt>, while <tt>off</tt> and <tt>no</tt> are boolean <tt>false</tt>.
</p>
<p>
For single-line statements, <tt>unless</tt> can be used as the inverse of <tt>if</tt>.
</p>
<p>
As a shortcut for <tt>this.property</tt>, you can use <tt>@property</tt>.
</p>
<p>
You can use <tt>in</tt> to test for array presence, and <tt>of</tt> to
test for JavaScript object-key presence.
</p>
<div class='code'><pre class="idle">launch() <span class="Keyword">if</span> ignition <span class="Keyword">is</span> <span class="BuiltInConstant">on</span>
volume <span class="Keyword">=</span> <span class="Number">10</span> <span class="Keyword">if</span> band <span class="Keyword">isnt</span> SpinalTap
letTheWildRumpusBegin() <span class="Keyword">unless</span> answer <span class="Keyword">is</span> <span class="BuiltInConstant">no</span>
<span class="Keyword">if</span> car.speed <span class="Keyword"><</span> limit <span class="Keyword">then</span> accelerate()
winner <span class="Keyword">=</span> <span class="BuiltInConstant">yes</span> <span class="Keyword">if</span> pick <span class="Keyword">in</span> [<span class="Number">47</span>, <span class="Number">92</span>, <span class="Number">13</span>]
print inspect <span class="String"><span class="String">"</span>My name is <span class="String">"</span></span> <span class="Keyword">+</span> <span class="Variable">@name</span>
</pre><pre class="idle"><span class="Storage">var</span> volume, winner;
<span class="Keyword">if</span> (ignition <span class="Keyword">===</span> <span class="BuiltInConstant">true</span>) {
launch();
}
<span class="Keyword">if</span> (band <span class="Keyword">!</span><span class="Keyword">==</span> SpinalTap) {
volume <span class="Keyword">=</span> <span class="Number">10</span>;
}
<span class="Keyword">if</span> (<span class="Keyword">!</span>(answer <span class="Keyword">===</span> <span class="BuiltInConstant">false</span>)) {
letTheWildRumpusBegin();
}
car.speed <span class="Keyword"><</span> limit ? accelerate() : <span class="BuiltInConstant">null</span>;
<span class="Keyword">if</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> <span class="Keyword">===</span> pick) {
winner <span class="Keyword">=</span> <span class="BuiltInConstant">true</span>;
}
<span class="LibraryFunction">print</span>(inspect(<span class="String"><span class="String">"</span>My name is <span class="String">"</span></span> <span class="Keyword">+</span> <span class="Variable">this</span>.<span class="LibraryConstant">name</span>));
</pre><br class='clear' /></div>
<p>
<span id="splats" class="bookmark"></span>
<b class="header">Splats...</b>
The JavaScript <b>arguments object</b> is a useful way to work with
functions that accept variable numbers of arguments. CoffeeScript provides
splats <tt>...</tt>, both for function definition as well as invocation,
making variable numbers of arguments a little bit more palatable.
</p>
<div class='code'><pre class="idle">gold <span class="Keyword">=</span> silver <span class="Keyword">=</span> rest <span class="Keyword">=</span> <span class="String"><span class="String">"</span>unknown<span class="String">"</span></span>
<span class="FunctionName">awardMedals </span><span class="Keyword">=</span> <span class="FunctionArgument">(</span><span class="FunctionArgument">first, second, others...</span><span class="FunctionArgument">)</span> <span class="Storage">-></span>
gold <span class="Keyword">=</span> first
silver <span class="Keyword">=</span> second
rest <span class="Keyword">=</span> others
contenders <span class="Keyword">=</span> [
<span class="String"><span class="String">"</span>Michael Phelps<span class="String">"</span></span>
<span class="String"><span class="String">"</span>Liu Xiang<span class="String">"</span></span>
<span class="String"><span class="String">"</span>Yao Ming<span class="String">"</span></span>
<span class="String"><span class="String">"</span>Allyson Felix<span class="String">"</span></span>
<span class="String"><span class="String">"</span>Shawn Johnson<span class="String">"</span></span>
<span class="String"><span class="String">"</span>Roman Sebrle<span class="String">"</span></span>
<span class="String"><span class="String">"</span>Guo Jingjing<span class="String">"</span></span>
<span class="String"><span class="String">"</span>Tyson Gay<span class="String">"</span></span>
<span class="String"><span class="String">"</span>Asafa Powell<span class="String">"</span></span>
<span class="String"><span class="String">"</span>Usain Bolt<span class="String">"</span></span>
]
awardMedals contenders...
alert <span class="String"><span class="String">"</span>Gold: <span class="String">"</span></span> <span class="Keyword">+</span> gold
alert <span class="String"><span class="String">"</span>Silver: <span class="String">"</span></span> <span class="Keyword">+</span> silver
alert <span class="String"><span class="String">"</span>The Field: <span class="String">"</span></span> <span class="Keyword">+</span> rest
</pre><pre class="idle"><span class="Storage">var</span> awardMedals, contenders, gold, rest, silver;
<span class="Storage">var</span> __slice <span class="Keyword">=</span> <span class="LibraryClassType">Array</span>.<span class="LibraryConstant">prototype</span>.slice;
gold <span class="Keyword">=</span> (silver <span class="Keyword">=</span> (rest <span class="Keyword">=</span> <span class="String"><span class="String">"</span>unknown<span class="String">"</span></span>));
<span class="FunctionName">awardMedals</span> = <span class="Storage">function</span>(<span class="FunctionArgument">first, second</span>) {
<span class="Storage">var</span> others;
others <span class="Keyword">=</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">"</span>Michael Phelps<span class="String">"</span></span>, <span class="String"><span class="String">"</span>Liu Xiang<span class="String">"</span></span>, <span class="String"><span class="String">"</span>Yao Ming<span class="String">"</span></span>, <span class="String"><span class="String">"</span>Allyson Felix<span class="String">"</span></span>, <span class="String"><span class="String">"</span>Shawn Johnson<span class="String">"</span></span>, <span class="String"><span class="String">"</span>Roman Sebrle<span class="String">"</span></span>, <span class="String"><span class="String">"</span>Guo Jingjing<span class="String">"</span></span>, <span class="String"><span class="String">"</span>Tyson Gay<span class="String">"</span></span>, <span class="String"><span class="String">"</span>Asafa Powell<span class="String">"</span></span>, <span class="String"><span class="String">"</span>Usain Bolt<span class="String">"</span></span>];
awardMedals.<span class="LibraryFunction">apply</span>(<span class="Variable">this</span>, contenders);
<span class="LibraryFunction">alert</span>(<span class="String"><span class="String">"</span>Gold: <span class="String">"</span></span> <span class="Keyword">+</span> gold);
<span class="LibraryFunction">alert</span>(<span class="String"><span class="String">"</span>Silver: <span class="String">"</span></span> <span class="Keyword">+</span> silver);
<span class="LibraryFunction">alert</span>(<span class="String"><span class="String">"</span>The Field: <span class="String">"</span></span> <span class="Keyword">+</span> rest);
</pre><button onclick='javascript: var awardMedals, contenders, gold, rest, silver;
var __slice = Array.prototype.slice;
gold = (silver = (rest = "unknown"));
awardMedals = function(first, second) {
var others;
others = __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(this, contenders);
alert("Gold: " + gold);
alert("Silver: " + silver);
alert("The Field: " + rest);;'>run</button><br class='clear' /></div>
<p>
<span id="while" class="bookmark"></span>
<b class="header">While, Until, and Loop</b>
The only low-level loop that CoffeeScript provides is the <b>while</b> loop. The
main difference from JavaScript is that the <b>while</b> loop can be used
as an expression, returning an array containing the result of each iteration
through the loop.
</p>
<div class='code'><pre class="idle"><span class="Comment"><span class="Comment">#</span> Econ 101</span>
<span class="Keyword">if</span> <span class="Variable">this</span>.studyingEconomics
buy() <span class="Keyword">while</span> supply <span class="Keyword">></span> demand
sell() <span class="Keyword">until</span> supply <span class="Keyword">></span> demand
<span class="Comment"><span class="Comment">#</span> Nursery Rhyme</span>
num <span class="Keyword">=</span> <span class="Number">6</span>
lyrics <span class="Keyword">=</span> <span class="Keyword">while</span> num <span class="Keyword">-</span><span class="Keyword">=</span> <span class="Number">1</span>
num <span class="Keyword">+</span> <span class="String"><span class="String">"</span> little monkeys, jumping on the bed.</span>
<span class="String"> One fell out and bumped his head.<span class="String">"</span></span>
</pre><pre class="idle"><span class="Storage">var</span> _a, lyrics, num;
<span class="Keyword">if</span> (<span class="Variable">this</span>.studyingEconomics) {
<span class="Keyword">while</span> (supply <span class="Keyword">></span> demand) {
buy();
}
<span class="Keyword">while</span> (<span class="Keyword">!</span>(supply <span class="Keyword">></span> demand)) {
sell();
}
}
num <span class="Keyword">=</span> <span class="Number">6</span>;
lyrics <span class="Keyword">=</span> (<span class="Storage">function</span>() {
_a <span class="Keyword">=</span> [];
<span class="Keyword">while</span> (num <span class="Keyword">-</span><span class="Keyword">=</span> <span class="Number">1</span>) {
_a.<span class="LibraryFunction">push</span>(num <span class="Keyword">+</span> <span class="String"><span class="String">"</span> little monkeys, jumping on the bed. \</span>
<span class="String">One fell out and bumped his head.<span class="String">"</span></span>);
}
<span class="Keyword">return</span> _a;
})();
</pre><button onclick='javascript: var _a, lyrics, num;
if (this.studyingEconomics) {
while (supply > demand) {
buy();
}
while (!(supply > demand)) {
sell();
}
}
num = 6;
lyrics = (function() {
_a = [];
while (num -= 1) {
_a.push(num + " little monkeys, jumping on the bed. \
One fell out and bumped his head.");
}
return _a;
})();;alert(lyrics.join("\n"));'>run: lyrics.join("\n")</button><br class='clear' /></div>
<p>
For readability, the <b>until</b> keyword is equivalent to <tt>while not</tt>,
and the <b>loop</b> keyword is equivalent to <tt>while true</tt>.
Other JavaScript loops, such as <b>for</b> loops and <b>do-while</b> loops
can be mimicked by variations on <b>loop</b>, but the hope is that you
won't need to do that with CoffeeScript, either because you're using
<b>each</b> (<b>forEach</b>) style iterators, or...
</p>
<p>
<span id="comprehensions" class="bookmark"></span>
<b class="header">Comprehensions (Arrays, Objects, and Ranges)</b>
For your looping needs, CoffeeScript provides array comprehensions
similar to Python's. They replace (and compile into) <b>for</b> loops, with
optional guard clauses and the value of the current array index.
Unlike for loops, array comprehensions are expressions, and can be returned
and assigned. They should be able to handle most places where you otherwise
would use a loop, <b>each</b>/<b>forEach</b>, <b>map</b>, or <b>select</b>/<b>filter</b>.
</p>
<div class='code'><pre class="idle"><span class="Comment"><span class="Comment">#</span> Eat lunch.</span>
lunch <span class="Keyword">=</span> eat food <span class="Keyword">for</span> food <span class="Keyword">in</span> [<span class="String"><span class="String">'</span>toast<span class="String">'</span></span>, <span class="String"><span class="String">'</span>cheese<span class="String">'</span></span>, <span class="String"><span class="String">'</span>wine<span class="String">'</span></span>]
<span class="Comment"><span class="Comment">#</span> Naive collision detection.</span>
<span class="Keyword">for</span> roid <span class="Keyword">in</span> asteroids
<span class="Keyword">for</span> roid2 <span class="Keyword">in</span> asteroids <span class="Keyword">when</span> roid <span class="Keyword">isnt</span> roid2
roid.explode() <span class="Keyword">if</span> roid.overlaps roid2
</pre><pre class="idle"><span class="Storage">var</span> _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, food, lunch, roid, roid2;
lunch <span class="Keyword">=</span> (<span class="Storage">function</span>() {
_a <span class="Keyword">=</span> []; _c <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> (_b <span class="Keyword">=</span> <span class="Number">0</span>, _d <span class="Keyword">=</span> _c.<span class="LibraryConstant">length</span>; _b <span class="Keyword"><</span> _d; _b<span class="Keyword">++</span>) {
food <span class="Keyword">=</span> _c[_b];
_a.<span class="LibraryFunction">push</span>(eat(food));
}
<span class="Keyword">return</span> _a;
})();
_f <span class="Keyword">=</span> asteroids;
<span class="Keyword">for</span> (_e <span class="Keyword">=</span> <span class="Number">0</span>, _g <span class="Keyword">=</span> _f.<span class="LibraryConstant">length</span>; _e <span class="Keyword"><</span> _g; _e<span class="Keyword">++</span>) {
roid <span class="Keyword">=</span> _f[_e];
_i <span class="Keyword">=</span> asteroids;
<span class="Keyword">for</span> (_h <span class="Keyword">=</span> <span class="Number">0</span>, _j <span class="Keyword">=</span> _i.<span class="LibraryConstant">length</span>; _h <span class="Keyword"><</span> _j; _h<span class="Keyword">++</span>) {
roid2 <span class="Keyword">=</span> _i[_h];
<span class="Keyword">if</span> (roid <span class="Keyword">!</span><span class="Keyword">==</span> roid2) {
<span class="Keyword">if</span> (roid.overlaps(roid2)) {
roid.explode();
}
}
}
}
</pre><br class='clear' /></div>
<p>
If you know the start and end of your loop, or would like to step through
in fixed-size increments, you can use a range to specify the start and
end of your comprehension.
</p>
<div class='code'><pre class="idle">countdown <span class="Keyword">=</span> num <span class="Keyword">for</span> num <span class="Keyword">in</span> [<span class="Number">10</span>..<span class="Number">1</span>]
<span class="FunctionName">deliverEggs </span><span class="Keyword">=</span> <span class="Storage">-></span>
<span class="Keyword">for</span> i <span class="Keyword">in</span> [<span class="Number">0</span>...eggs.length] <span class="Keyword">by</span> <span class="Number">12</span>
dozen <span class="Keyword">=</span> eggs[i...i<span class="Keyword">+</span><span class="Number">12</span>]
deliver <span class="Keyword">new</span> <span class="TypeName">eggCarton</span> dozen
</pre><pre class="idle"><span class="Storage">var</span> _a, countdown, deliverEggs, num;
countdown <span class="Keyword">=</span> (<span class="Storage">function</span>() {
_a <span class="Keyword">=</span> [];
<span class="Keyword">for</span> (num <span class="Keyword">=</span> <span class="Number">10</span>; num <span class="Keyword">>=</span> <span class="Number">1</span>; num<span class="Keyword">--</span>) {
_a.<span class="LibraryFunction">push</span>(num);
}
<span class="Keyword">return</span> _a;
})();
<span class="FunctionName">deliverEggs</span> = <span class="Storage">function</span>() {
<span class="Storage">var</span> _b, _c, dozen, i;
_b <span class="Keyword">=</span> []; _c <span class="Keyword">=</span> eggs.<span class="LibraryConstant">length</span>;
<span class="Keyword">for</span> (i <span class="Keyword">=</span> <span class="Number">0</span>; (<span class="Number">0</span> <span class="Keyword"><=</span> _c ? i <span class="Keyword"><</span> _c : i <span class="Keyword">></span> _c); i <span class="Keyword">+</span><span class="Keyword">=</span> <span class="Number">12</span>) {
_b.<span class="LibraryFunction">push</span>((<span class="Storage">function</span>() {
dozen <span class="Keyword">=</span> eggs.<span class="LibraryFunction">slice</span>(i, i <span class="Keyword">+</span> <span class="Number">12</span>);
<span class="Keyword">return</span> deliver(<span class="Keyword">new</span> <span class="TypeName">eggCarton</span>(dozen));
})());
}
<span class="Keyword">return</span> _b;
};
</pre><button onclick='javascript: var _a, countdown, deliverEggs, num;
countdo