PageRenderTime 71ms CodeModel.GetById 20ms app.highlight 33ms RepoModel.GetById 1ms app.codeStats 1ms

/index.html

http://github.com/jashkenas/coffee-script
HTML | 3694 lines | 3274 code | 420 blank | 0 comment | 0 complexity | 937a7822ad1ff30897820ca398114b4a MD5 | raw file

Large files files are truncated, but you can click here to view the full file

   1<!DOCTYPE html>
   2<html>
   3<head>
   4  <meta http-equiv="content-type" content="text/html;charset=UTF-8" />
   5  <title>CoffeeScript</title>
   6  <meta name="viewport" content="width=device-width, initial-scale=1" />
   7  <link rel="canonical" href="http://coffeescript.org" />
   8  <link rel="stylesheet" type="text/css" href="documentation/css/docs.css" />
   9  <link rel="stylesheet" type="text/css" href="documentation/css/tomorrow.css" />
  10  <link rel="shortcut icon" href="documentation/images/favicon.ico" />
  11</head>
  12<body>
  13
  14  <div id="fadeout"></div>
  15
  16  <div id="flybar">
  17    <a id="logo" href="#top"><img src="documentation/images/logo.png" width="225" height="39" alt="CoffeeScript" /></a>
  18    <div class="navigation toc">
  19      <div class="button">
  20        Table of Contents
  21      </div>
  22      <div class="contents menu">
  23        <a href="#overview">Overview</a>
  24        <a href="#installation">Installation</a>
  25        <a href="#usage">Usage</a>
  26        <a href="#literate">Literate CoffeeScript</a>
  27        <a href="#language">Language Reference</a>
  28        <a href="#literals">Literals: Functions, Objects and Arrays</a>
  29        <a href="#lexical-scope">Lexical Scoping and Variable Safety</a>
  30        <a href="#conditionals">If, Else, Unless, and Conditional Assignment</a>
  31        <a href="#splats">Splats...</a>
  32        <a href="#loops">Loops and Comprehensions</a>
  33        <a href="#slices">Array Slicing and Splicing</a>
  34        <a href="#expressions">Everything is an Expression</a>
  35        <a href="#operators">Operators and Aliases</a>
  36        <a href="#classes">Classes, Inheritance, and Super</a>
  37        <a href="#destructuring">Destructuring Assignment</a>
  38        <a href="#fat-arrow">Bound and Generator Functions</a>
  39        <a href="#embedded">Embedded JavaScript</a>
  40        <a href="#switch">Switch and Try/Catch</a>
  41        <a href="#comparisons">Chained Comparisons</a>
  42        <a href="#strings">String Interpolation, Block Strings, and Block Comments</a>
  43        <a href="#regexes">Block Regular Expressions</a>
  44        <a href="#cake">Cake, and Cakefiles</a>
  45        <a href="#source-maps">Source Maps</a>
  46        <a href="#scripts">"text/coffeescript" Script Tags</a>
  47        <a href="#resources">Books, Screencasts, Examples and Resources</a>
  48        <a href="#changelog">Change Log</a>
  49      </div>
  50    </div>
  51    <div class="navigation try">
  52      <div class="button">
  53        Try CoffeeScript
  54        <div class="repl_bridge"></div>
  55      </div>
  56      <div class="contents repl_wrapper">
  57        <div class="code">
  58          <div class="screenshadow tl"></div>
  59          <div class="screenshadow tr"></div>
  60          <div class="screenshadow bl"></div>
  61          <div class="screenshadow br"></div>
  62          <div id="repl_source_wrap">
  63            <textarea id="repl_source" rows="100" spellcheck="false">alert "Hello CoffeeScript!"</textarea>
  64          </div>
  65          <div id="repl_results_wrap"><pre id="repl_results"></pre></div>
  66          <div class="minibutton dark run" title="Ctrl-Enter">Run</div>
  67          <a class="minibutton permalink" id="repl_permalink">Link</a>
  68          <br class="clear" />
  69        </div>
  70      </div>
  71    </div>
  72    <div class="navigation annotated">
  73      <div class="button">
  74        Annotated Source
  75      </div>
  76      <div class="contents menu">
  77        <a href="documentation/docs/grammar.html">Grammar Rules &mdash; src/grammar</a>
  78        <a href="documentation/docs/lexer.html">Lexing Tokens &mdash; src/lexer</a>
  79        <a href="documentation/docs/rewriter.html">The Rewriter &mdash; src/rewriter</a>
  80        <a href="documentation/docs/nodes.html">The Syntax Tree &mdash; src/nodes</a>
  81        <a href="documentation/docs/scope.html">Lexical Scope &mdash; src/scope</a>
  82        <a href="documentation/docs/helpers.html">Helpers &amp; Utility Functions &mdash; src/helpers</a>
  83        <a href="documentation/docs/coffee-script.html">The CoffeeScript Module &mdash; src/coffee-script</a>
  84        <a href="documentation/docs/cake.html">Cake &amp; Cakefiles &mdash; src/cake</a>
  85        <a href="documentation/docs/command.html">"coffee" Command-Line Utility &mdash; src/command</a>
  86        <a href="documentation/docs/optparse.html">Option Parsing &mdash; src/optparse</a>
  87        <a href="documentation/docs/repl.html">Interactive REPL &mdash; src/repl</a>
  88        <a href="documentation/docs/sourcemap.html">Source Maps &mdash; src/sourcemap</a>
  89      </div>
  90    </div>
  91  </div>
  92
  93  <div class="container">
  94    <span class="bookmark" id="top"></span>
  95
  96    <p>
  97      <b>CoffeeScript is a little language that compiles into JavaScript.</b>
  98      Underneath that awkward Java-esque patina, JavaScript has always had
  99      a gorgeous heart. CoffeeScript is an attempt to expose
 100      the good parts of JavaScript in a simple way.
 101    </p>
 102
 103    <p>
 104      The golden rule of CoffeeScript is: <i>"It's just JavaScript"</i>. The code
 105      compiles one-to-one into the equivalent JS, and there is
 106      no interpretation at runtime. You can use any existing JavaScript library
 107      seamlessly from CoffeeScript (and vice-versa). The compiled output is
 108      readable and pretty-printed, will work in every JavaScript runtime, and tends
 109      to run as fast or faster than the equivalent handwritten JavaScript.
 110    </p>
 111
 112    <p>
 113      <b>Latest Version:</b>
 114      <a href="http://github.com/jashkenas/coffeescript/tarball/1.10.0">1.10.0</a>
 115    </p>
 116
 117    <pre>npm install -g coffee-script</pre>
 118
 119    <h2>
 120      <span id="overview" class="bookmark"></span>
 121      Overview
 122    </h2>
 123
 124    <p><i>CoffeeScript on the left, compiled JavaScript output on the right.</i></p>
 125
 126    <div class='code'><pre><code><span class="comment"># Assignment:</span>
 127number   = <span class="number">42</span>
 128opposite = <span class="literal">true</span>
 129
 130<span class="comment"># Conditions:</span>
 131number = -<span class="number">42</span> <span class="keyword">if</span> opposite
 132
 133<span class="comment"># Functions:</span>
 134<span class="function"><span class="title">square</span> = <span class="params">(x)</span> -&gt;</span> x * x
 135
 136<span class="comment"># Arrays:</span>
 137list = [<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>]
 138
 139<span class="comment"># Objects:</span>
 140math =
 141  <span class="attribute">root</span>:   Math.sqrt
 142  <span class="attribute">square</span>: square
 143  <span class="attribute">cube</span>:   <span class="function"><span class="params">(x)</span> -&gt;</span> x * square x
 144
 145<span class="comment"># Splats:</span>
 146<span class="function"><span class="title">race</span> = <span class="params">(winner, runners...)</span> -&gt;</span>
 147  <span class="built_in">print</span> winner, runners
 148
 149<span class="comment"># Existence:</span>
 150alert <span class="string">"I knew it!"</span> <span class="keyword">if</span> elvis?
 151
 152<span class="comment"># Array comprehensions:</span>
 153cubes = (math.cube num <span class="keyword">for</span> num <span class="keyword">in</span> list)
 154</code></pre><pre><code><span class="keyword">var</span> cubes, list, math, num, number, opposite, race, square,
 155  slice = [].slice;
 156
 157number = <span class="number">42</span>;
 158
 159opposite = <span class="literal">true</span>;
 160
 161<span class="keyword">if</span> (opposite) {
 162  number = -<span class="number">42</span>;
 163}
 164
 165square = <span class="function"><span class="keyword">function</span><span class="params">(x)</span> {</span>
 166  <span class="keyword">return</span> x * x;
 167};
 168
 169list = [<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>];
 170
 171math = {
 172  root: <span class="built_in">Math</span>.sqrt,
 173  square: square,
 174  cube: <span class="function"><span class="keyword">function</span><span class="params">(x)</span> {</span>
 175    <span class="keyword">return</span> x * square(x);
 176  }
 177};
 178
 179race = <span class="function"><span class="keyword">function</span><span class="params">()</span> {</span>
 180  <span class="keyword">var</span> runners, winner;
 181  winner = <span class="built_in">arguments</span>[<span class="number">0</span>], runners = <span class="number">2</span> &lt;= <span class="built_in">arguments</span>.length ? slice.call(<span class="built_in">arguments</span>, <span class="number">1</span>) : [];
 182  <span class="keyword">return</span> print(winner, runners);
 183};
 184
 185<span class="keyword">if</span> (<span class="keyword">typeof</span> elvis !== <span class="string">"undefined"</span> &amp;&amp; elvis !== <span class="literal">null</span>) {
 186  alert(<span class="string">"I knew it!"</span>);
 187}
 188
 189cubes = (<span class="function"><span class="keyword">function</span><span class="params">()</span> {</span>
 190  <span class="keyword">var</span> i, len, results;
 191  results = [];
 192  <span class="keyword">for</span> (i = <span class="number">0</span>, len = list.length; i &lt; len; i++) {
 193    num = list[i];
 194    results.push(math.cube(num));
 195  }
 196  <span class="keyword">return</span> results;
 197})();
 198</code></pre><script>window.example1 = "# Assignment:\nnumber   = 42\nopposite = true\n\n# Conditions:\nnumber = -42 if opposite\n\n# Functions:\nsquare = (x) -> x * x\n\n# Arrays:\nlist = [1, 2, 3, 4, 5]\n\n# Objects:\nmath =\n  root:   Math.sqrt\n  square: square\n  cube:   (x) -> x * square x\n\n# Splats:\nrace = (winner, runners...) ->\n  print winner, runners\n\n# Existence:\nalert \"I knew it!\" if elvis?\n\n# Array comprehensions:\ncubes = (math.cube num for num in list)\n"</script><div class='minibutton ok' onclick='javascript: var cubes, list, math, num, number, opposite, race, square,
 199  slice = [].slice;
 200
 201number = 42;
 202
 203opposite = true;
 204
 205if (opposite) {
 206  number = -42;
 207}
 208
 209square = function(x) {
 210  return x * x;
 211};
 212
 213list = [1, 2, 3, 4, 5];
 214
 215math = {
 216  root: Math.sqrt,
 217  square: square,
 218  cube: function(x) {
 219    return x * square(x);
 220  }
 221};
 222
 223race = function() {
 224  var runners, winner;
 225  winner = arguments[0], runners = 2 <= arguments.length ? slice.call(arguments, 1) : [];
 226  return print(winner, runners);
 227};
 228
 229if (typeof elvis !== "undefined" && elvis !== null) {
 230  alert("I knew it!");
 231}
 232
 233cubes = (function() {
 234  var i, len, results;
 235  results = [];
 236  for (i = 0, len = list.length; i < len; i++) {
 237    num = list[i];
 238    results.push(math.cube(num));
 239  }
 240  return results;
 241})();
 242;alert(cubes);'>run: cubes</div><br class='clear' /></div>
 243
 244    <h2>
 245      <span id="installation" class="bookmark"></span>
 246      Installation
 247    </h2>
 248
 249    <p>
 250      The CoffeeScript compiler is itself
 251      <a href="documentation/docs/grammar.html">written in CoffeeScript</a>,
 252      using the <a href="http://jison.org">Jison parser generator</a>. The
 253      command-line version of <code>coffee</code> is available as a
 254      <a href="http://nodejs.org/">Node.js</a> utility. The
 255      <a href="extras/coffee-script.js">core compiler</a> however, does not
 256      depend on Node, and can be run in any JavaScript environment, or in the
 257      browser (see "Try CoffeeScript", above).
 258    </p>
 259
 260    <p>
 261      To install, first make sure you have a working copy of the latest stable version of
 262      <a href="http://nodejs.org/">Node.js</a>. You can then install CoffeeScript globally
 263      with <a href="http://npmjs.org">npm</a>:
 264    </p>
 265
 266    <pre>
 267npm install -g coffee-script</pre>
 268
 269    <p>
 270      When you need CoffeeScript as a dependency, install it locally:
 271    </p>
 272
 273    <pre>
 274npm install --save coffee-script</pre>
 275
 276    <p>
 277      If you'd prefer to install the latest <b>master</b> version of CoffeeScript, you
 278      can clone the CoffeeScript
 279      <a href="http://github.com/jashkenas/coffeescript">source repository</a>
 280      from GitHub, or download
 281      <a href="http://github.com/jashkenas/coffeescript/tarball/master">the source</a> directly.
 282      To install the latest master CoffeeScript compiler with npm:
 283    </p>
 284
 285<pre>
 286npm install -g jashkenas/coffeescript</pre>
 287
 288    <p>
 289      Or, if you want to install to <code>/usr/local</code>, and don't want to use
 290      npm to manage it, open the <code>coffee-script</code> directory and run:
 291    </p>
 292
 293  <pre>
 294sudo bin/cake install</pre>
 295
 296    <h2>
 297      <span id="usage" class="bookmark"></span>
 298      Usage
 299    </h2>
 300
 301    <p>
 302      Once installed, you should have access to the <code>coffee</code> command,
 303      which can execute scripts, compile <code>.coffee</code> files into <code>.js</code>,
 304      and provide an interactive REPL. The <code>coffee</code> command takes the
 305      following options:
 306    </p>
 307
 308    <table>
 309      <tr>
 310        <td><code>-c, --compile</code></td>
 311        <td>
 312          Compile a <code>.coffee</code> script into a <code>.js</code> JavaScript file
 313          of the same name.
 314        </td>
 315      </tr>
 316      <tr>
 317        <td><code>-m, --map</code></td>
 318        <td>
 319          Generate source maps alongside the compiled JavaScript files. Adds
 320          <code>sourceMappingURL</code> directives to the JavaScript as well.
 321        </td>
 322      </tr>
 323      <tr>
 324        <td width="25%"><code>-i, --interactive</code></td>
 325        <td>
 326          Launch an interactive CoffeeScript session to try short snippets.
 327          Identical to calling <code>coffee</code> with no arguments.
 328        </td>
 329      </tr>
 330      <tr>
 331        <td><code>-o, --output [DIR]</code></td>
 332        <td>
 333          Write out all compiled JavaScript files into the specified directory.
 334          Use in conjunction with <code>--compile</code> or <code>--watch</code>.
 335        </td>
 336      </tr>
 337      <tr>
 338        <td><code>-j, --join [FILE]</code></td>
 339        <td>
 340          Before compiling, concatenate all scripts together in the order they
 341          were passed, and write them into the specified file.
 342          Useful for building large projects.
 343        </td>
 344      </tr>
 345      <tr>
 346        <td><code>-w, --watch</code></td>
 347        <td>
 348          Watch files for changes, rerunning the specified command when any
 349          file is updated.
 350        </td>
 351      </tr>
 352      <tr>
 353        <td><code>-p, --print</code></td>
 354        <td>
 355          Instead of writing out the JavaScript as a file, print it
 356          directly to <b>stdout</b>.
 357        </td>
 358      </tr>
 359      <tr>
 360        <td><code>-s, --stdio</code></td>
 361        <td>
 362          Pipe in CoffeeScript to STDIN and get back JavaScript over STDOUT.
 363          Good for use with processes written in other languages. An example:<br />
 364          <code>cat src/cake.coffee | coffee -sc</code>
 365        </td>
 366      </tr>
 367      <tr>
 368        <td><code>-l, --literate</code></td>
 369        <td>
 370          Parses the code as Literate CoffeeScript. You only need to specify
 371          this when passing in code directly over <b>stdio</b>, or using some sort
 372          of extension-less file name.
 373        </td>
 374      </tr>
 375      <tr>
 376        <td><code>-e, --eval</code></td>
 377        <td>
 378          Compile and print a little snippet of CoffeeScript directly from the
 379          command line. For example:<br /><code>coffee -e "console.log num for num in [10..1]"</code>
 380        </td>
 381      </tr>
 382      <tr>
 383        <td><code>-b, --bare</code></td>
 384        <td>
 385          Compile the JavaScript without the
 386          <a href="#lexical-scope">top-level function safety wrapper</a>.
 387        </td>
 388      </tr>
 389      <tr>
 390        <td><code>-t, --tokens</code></td>
 391        <td>
 392          Instead of parsing the CoffeeScript, just lex it, and print out the
 393          token stream: <code>[IDENTIFIER square] [ASSIGN =] [PARAM_START (]</code> ...
 394        </td>
 395      </tr>
 396      <tr>
 397        <td><code>-n, --nodes</code></td>
 398        <td>
 399          Instead of compiling the CoffeeScript, just lex and parse it, and print
 400          out the parse tree:
 401<pre class="no_bar">
 402Expressions
 403  Assign
 404    Value "square"
 405    Code "x"
 406      Op *
 407        Value "x"
 408        Value "x"</pre>
 409        </td>
 410      </tr>
 411      <tr>
 412        <td><code>--nodejs</code></td>
 413        <td>
 414          The <code>node</code> executable has some useful options you can set,
 415          such as<br /> <code>--debug</code>, <code>--debug-brk</code>, <code>--max-stack-size</code>,
 416          and <code>--expose-gc</code>. Use this flag to forward options directly to Node.js.
 417          To pass multiple flags, use <code>--nodejs</code> multiple times.
 418        </td>
 419      </tr>
 420    </table>
 421
 422    <p>
 423      <b>Examples:</b>
 424    </p>
 425
 426    <ul>
 427      <li>
 428        Compile a directory tree of <code>.coffee</code> files in <code>src</code> into a parallel
 429        tree of <code>.js</code> files in <code>lib</code>:<br />
 430        <code>coffee --compile --output lib/ src/</code>
 431      </li>
 432      <li>
 433        Watch a file for changes, and recompile it every time the file is saved:<br />
 434        <code>coffee --watch --compile experimental.coffee</code>
 435      </li>
 436      <li>
 437        Concatenate a list of files into a single script:<br />
 438        <code>coffee --join project.js --compile src/*.coffee</code>
 439      </li>
 440      <li>
 441        Print out the compiled JS from a one-liner:<br />
 442        <code>coffee -bpe "alert i for i in [0..10]"</code>
 443      </li>
 444      <li>
 445        All together now, watch and recompile an entire project as you work on it:<br />
 446        <code>coffee -o lib/ -cw src/</code>
 447      </li>
 448      <li>
 449        Start the CoffeeScript REPL (<code>Ctrl-D</code> to exit, <code>Ctrl-V</code>for multi-line):<br />
 450        <code>coffee</code>
 451      </li>
 452    </ul>
 453
 454    <h2>
 455      <span id="literate" class="bookmark"></span>
 456      Literate CoffeeScript
 457    </h2>
 458
 459    <p>
 460      Besides being used as an ordinary programming language, CoffeeScript may
 461      also be written in "literate" mode. If you name your file with a
 462      <code>.litcoffee</code> extension, you can write it as a Markdown document &mdash;
 463      a document that also happens to be executable CoffeeScript code. The compiler
 464      will treat any indented blocks (Markdown's way of indicating source code)
 465      as code, and ignore the rest as comments.
 466    </p>
 467
 468    <p>
 469      Just for kicks, a little bit of the compiler is currently implemented in this fashion:
 470      See it
 471      <a href="https://gist.github.com/jashkenas/3fc3c1a8b1009c00d9df">as a document</a>,
 472      <a href="https://raw.github.com/jashkenas/coffeescript/master/src/scope.litcoffee">raw</a>,
 473      and <a href="http://cl.ly/LxEu">properly highlighted in a text editor</a>.
 474    </p>
 475
 476    <p>
 477      I'm fairly excited about this direction for the language, and am looking
 478      forward to writing (and more importantly, reading) more programs in this style.
 479      More information about Literate CoffeeScript, including an
 480      <a href="https://github.com/jashkenas/journo">example program</a>,
 481      are <a href="http://ashkenas.com/literate-coffeescript">available in this blog post</a>.
 482    </p>
 483
 484    <h2>
 485      <span id="language" class="bookmark"></span>
 486      Language Reference
 487    </h2>
 488
 489    <p>
 490      <i>
 491        This reference is structured so that it can be read from top to bottom,
 492        if you like. Later sections use ideas and syntax previously introduced.
 493        Familiarity with JavaScript is assumed.
 494        In all of the following examples, the source CoffeeScript is provided on
 495        the left, and the direct compilation into JavaScript is on the right.
 496      </i>
 497    </p>
 498
 499    <p>
 500      <i>
 501        Many of the examples can be run (where it makes sense) by pressing the <b>run</b>
 502        button on the right, and can be loaded into the "Try CoffeeScript"
 503        console by pressing the <b>load</b> button on the left.
 504      </i>
 505    <p>
 506      First, the basics: CoffeeScript uses significant whitespace to delimit blocks of code.
 507      You don't need to use semicolons <code>;</code> to terminate expressions,
 508      ending the line will do just as well (although semicolons can still
 509      be used to fit multiple expressions onto a single line).
 510      Instead of using curly braces
 511      <code>{ }</code> to surround blocks of code in <a href="#literals">functions</a>,
 512      <a href="#conditionals">if-statements</a>,
 513      <a href="#switch">switch</a>, and <a href="#try">try/catch</a>,
 514      use indentation.
 515    </p>
 516
 517    <p>
 518      You don't need to use parentheses to invoke a function if you're passing
 519      arguments. The implicit call wraps forward to the end of the line or block expression.<br />
 520      <code>console.log sys.inspect object</code> &rarr; <code>console.log(sys.inspect(object));</code>
 521    </p>
 522
 523    <p>
 524      <span id="literals" class="bookmark"></span>
 525      <b class="header">Functions</b>
 526      Functions are defined by an optional list of parameters in parentheses,
 527      an arrow, and the function body. The empty function looks like this:
 528      <code>-></code>
 529    </p>
 530    <div class='code'><pre><code><span class="function"><span class="title">square</span> = <span class="params">(x)</span> -&gt;</span> x * x
 531<span class="function"><span class="title">cube</span>   = <span class="params">(x)</span> -&gt;</span> square(x) * x
 532</code></pre><pre><code><span class="keyword">var</span> cube, square;
 533
 534square = <span class="function"><span class="keyword">function</span><span class="params">(x)</span> {</span>
 535  <span class="keyword">return</span> x * x;
 536};
 537
 538cube = <span class="function"><span class="keyword">function</span><span class="params">(x)</span> {</span>
 539  <span class="keyword">return</span> square(x) * x;
 540};
 541</code></pre><script>window.example2 = "square = (x) -> x * x\ncube   = (x) -> square(x) * x\n"</script><div class='minibutton load' onclick='javascript: loadConsole(example2);'>load</div><div class='minibutton ok' onclick='javascript: var cube, square;
 542
 543square = function(x) {
 544  return x * x;
 545};
 546
 547cube = function(x) {
 548  return square(x) * x;
 549};
 550;alert(cube(5));'>run: cube(5)</div><br class='clear' /></div>
 551    <p>
 552      Functions may also have default values for arguments, which will be used
 553      if the incoming argument is missing (<code>null</code> or <code>undefined</code>).
 554    </p>
 555    <div class='code'><pre><code><span class="function"><span class="title">fill</span> = <span class="params">(container, liquid = <span class="string">"coffee"</span>)</span> -&gt;</span>
 556  <span class="string">"Filling the <span class="subst">#{container}</span> with <span class="subst">#{liquid}</span>..."</span>
 557</code></pre><pre><code><span class="keyword">var</span> fill;
 558
 559fill = <span class="function"><span class="keyword">function</span><span class="params">(container, liquid)</span> {</span>
 560  <span class="keyword">if</span> (liquid == <span class="literal">null</span>) {
 561    liquid = <span class="string">"coffee"</span>;
 562  }
 563  <span class="keyword">return</span> <span class="string">"Filling the "</span> + container + <span class="string">" with "</span> + liquid + <span class="string">"..."</span>;
 564};
 565</code></pre><script>window.example3 = "fill = (container, liquid = \"coffee\") ->\n  \"Filling the #{container} with #{liquid}...\"\n"</script><div class='minibutton load' onclick='javascript: loadConsole(example3);'>load</div><div class='minibutton ok' onclick='javascript: var fill;
 566
 567fill = function(container, liquid) {
 568  if (liquid == null) {
 569    liquid = "coffee";
 570  }
 571  return "Filling the " + container + " with " + liquid + "...";
 572};
 573;alert(fill("cup"));'>run: fill("cup")</div><br class='clear' /></div>
 574
 575    <p>
 576      <span id="objects_and_arrays" class="bookmark"></span>
 577      <b class="header">Objects and Arrays</b>
 578      The CoffeeScript literals for objects and arrays look very similar to
 579      their JavaScript cousins. When each property is listed on its own line,
 580      the commas are optional. Objects may be created using indentation instead
 581      of explicit braces, similar to <a href="http://yaml.org">YAML</a>.
 582    </p>
 583    <div class='code'><pre><code>song = [<span class="string">"do"</span>, <span class="string">"re"</span>, <span class="string">"mi"</span>, <span class="string">"fa"</span>, <span class="string">"so"</span>]
 584
 585singers = {<span class="attribute">Jagger</span>: <span class="string">"Rock"</span>, <span class="attribute">Elvis</span>: <span class="string">"Roll"</span>}
 586
 587bitlist = [
 588  <span class="number">1</span>, <span class="number">0</span>, <span class="number">1</span>
 589  <span class="number">0</span>, <span class="number">0</span>, <span class="number">1</span>
 590  <span class="number">1</span>, <span class="number">1</span>, <span class="number">0</span>
 591]
 592
 593kids =
 594  <span class="attribute">brother</span>:
 595    <span class="attribute">name</span>: <span class="string">"Max"</span>
 596    <span class="attribute">age</span>:  <span class="number">11</span>
 597  <span class="attribute">sister</span>:
 598    <span class="attribute">name</span>: <span class="string">"Ida"</span>
 599    <span class="attribute">age</span>:  <span class="number">9</span>
 600</code></pre><pre><code><span class="keyword">var</span> bitlist, kids, singers, song;
 601
 602song = [<span class="string">"do"</span>, <span class="string">"re"</span>, <span class="string">"mi"</span>, <span class="string">"fa"</span>, <span class="string">"so"</span>];
 603
 604singers = {
 605  Jagger: <span class="string">"Rock"</span>,
 606  Elvis: <span class="string">"Roll"</span>
 607};
 608
 609bitlist = [<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>];
 610
 611kids = {
 612  brother: {
 613    name: <span class="string">"Max"</span>,
 614    age: <span class="number">11</span>
 615  },
 616  sister: {
 617    name: <span class="string">"Ida"</span>,
 618    age: <span class="number">9</span>
 619  }
 620};
 621</code></pre><script>window.example4 = "song = [\"do\", \"re\", \"mi\", \"fa\", \"so\"]\n\nsingers = {Jagger: \"Rock\", Elvis: \"Roll\"}\n\nbitlist = [\n  1, 0, 1\n  0, 0, 1\n  1, 1, 0\n]\n\nkids =\n  brother:\n    name: \"Max\"\n    age:  11\n  sister:\n    name: \"Ida\"\n    age:  9\n"</script><div class='minibutton load' onclick='javascript: loadConsole(example4);'>load</div><div class='minibutton ok' onclick='javascript: var bitlist, kids, singers, song;
 622
 623song = ["do", "re", "mi", "fa", "so"];
 624
 625singers = {
 626  Jagger: "Rock",
 627  Elvis: "Roll"
 628};
 629
 630bitlist = [1, 0, 1, 0, 0, 1, 1, 1, 0];
 631
 632kids = {
 633  brother: {
 634    name: "Max",
 635    age: 11
 636  },
 637  sister: {
 638    name: "Ida",
 639    age: 9
 640  }
 641};
 642;alert(song.join(" ... "));'>run: song.join(" ... ")</div><br class='clear' /></div>
 643    <p>
 644      In JavaScript, you can't use reserved words, like <code>class</code>, as properties
 645      of an object, without quoting them as strings. CoffeeScript notices reserved words
 646      used as keys in objects and quotes them for you, so you don't have to worry
 647      about it (say, when using jQuery).
 648    </p>
 649    <div class='code'><pre><code>$('.account').attr class: 'active'
 650
 651log object.class
 652</code></pre><pre><code>$(<span class="string">'.account'</span>).attr({
 653  <span class="string">"class"</span>: <span class="string">'active'</span>
 654});
 655
 656log(object[<span class="string">"class"</span>]);
 657</code></pre><script>window.example5 = "$('.account').attr class: 'active'\n\nlog object.class\n"</script><div class='minibutton load' onclick='javascript: loadConsole(example5);'>load</div><br class='clear' /></div>
 658
 659    <p>
 660      <span id="lexical-scope" class="bookmark"></span>
 661      <b class="header">Lexical Scoping and Variable Safety</b>
 662      The CoffeeScript compiler takes care to make sure that all of your variables
 663      are properly declared within lexical scope &mdash; you never need to write
 664      <code>var</code> yourself.
 665    </p>
 666    <div class='code'><pre><code>outer = <span class="number">1</span>
 667<span class="function"><span class="title">changeNumbers</span> = -&gt;</span>
 668  inner = -<span class="number">1</span>
 669  outer = <span class="number">10</span>
 670inner = changeNumbers()</code></pre><pre><code><span class="keyword">var</span> changeNumbers, inner, outer;
 671
 672outer = <span class="number">1</span>;
 673
 674changeNumbers = <span class="function"><span class="keyword">function</span><span class="params">()</span> {</span>
 675  <span class="keyword">var</span> inner;
 676  inner = -<span class="number">1</span>;
 677  <span class="keyword">return</span> outer = <span class="number">10</span>;
 678};
 679
 680inner = changeNumbers();
 681</code></pre><script>window.example6 = "outer = 1\nchangeNumbers = ->\n  inner = -1\n  outer = 10\ninner = changeNumbers()"</script><div class='minibutton load' onclick='javascript: loadConsole(example6);'>load</div><div class='minibutton ok' onclick='javascript: var changeNumbers, inner, outer;
 682
 683outer = 1;
 684
 685changeNumbers = function() {
 686  var inner;
 687  inner = -1;
 688  return outer = 10;
 689};
 690
 691inner = changeNumbers();
 692;alert(inner);'>run: inner</div><br class='clear' /></div>
 693    <p>
 694      Notice how all of the variable declarations have been pushed up to
 695      the top of the closest scope, the first time they appear.
 696      <b>outer</b> is not redeclared within the inner function, because it's
 697      already in scope; <b>inner</b> within the function, on the other hand,
 698      should not be able to change the value of the external variable of the same name, and
 699      therefore has a declaration of its own.
 700    </p>
 701    <p>
 702      This behavior is effectively identical to Ruby's scope for local variables.
 703      Because you don't have direct access to the <code>var</code> keyword,
 704      it's impossible to shadow an outer variable on purpose, you may only refer
 705      to it. So be careful that you're not reusing the name of an external
 706      variable accidentally, if you're writing a deeply nested function.
 707    </p>
 708    <p>
 709      Although suppressed within this documentation for clarity, all
 710      CoffeeScript output is wrapped in an anonymous function:
 711      <code>(function(){ ... })();</code> This safety wrapper, combined with the
 712      automatic generation of the <code>var</code> keyword, make it exceedingly difficult
 713      to pollute the global namespace by accident.
 714    </p>
 715    <p>
 716      If you'd like to create top-level variables for other scripts to use,
 717      attach them as properties on <b>window</b>, or on the <b>exports</b>
 718      object in CommonJS. The <b>existential operator</b> (covered below), gives you a
 719      reliable way to figure out where to add them; if you're targeting both
 720      CommonJS and the browser: <code>exports ? this</code>
 721    </p>
 722
 723    <p>
 724      <span id="conditionals" class="bookmark"></span>
 725      <b class="header">If, Else, Unless, and Conditional Assignment</b>
 726      <b>If/else</b> statements can be written without the use of parentheses and
 727      curly brackets. As with functions and other block expressions,
 728      multi-line conditionals are delimited by indentation. There's also a handy
 729      postfix form, with the <code>if</code> or <code>unless</code> at the end.
 730    </p>
 731    <p>
 732      CoffeeScript can compile <b>if</b> statements into JavaScript expressions,
 733      using the ternary operator when possible, and closure wrapping otherwise. There
 734      is no explicit ternary statement in CoffeeScript &mdash; you simply use
 735      a regular <b>if</b> statement on a single line.
 736    </p>
 737    <div class='code'><pre><code>mood = greatlyImproved <span class="keyword">if</span> singing
 738
 739<span class="keyword">if</span> happy <span class="keyword">and</span> knowsIt
 740  clapsHands()
 741  chaChaCha()
 742<span class="keyword">else</span>
 743  showIt()
 744
 745date = <span class="keyword">if</span> friday <span class="keyword">then</span> sue <span class="keyword">else</span> jill
 746</code></pre><pre><code><span class="keyword">var</span> date, mood;
 747
 748<span class="keyword">if</span> (singing) {
 749  mood = greatlyImproved;
 750}
 751
 752<span class="keyword">if</span> (happy &amp;&amp; knowsIt) {
 753  clapsHands();
 754  chaChaCha();
 755} <span class="keyword">else</span> {
 756  showIt();
 757}
 758
 759date = friday ? sue : jill;
 760</code></pre><script>window.example7 = "mood = greatlyImproved if singing\n\nif happy and knowsIt\n  clapsHands()\n  chaChaCha()\nelse\n  showIt()\n\ndate = if friday then sue else jill\n"</script><div class='minibutton load' onclick='javascript: loadConsole(example7);'>load</div><br class='clear' /></div>
 761
 762    <p>
 763      <span id="splats" class="bookmark"></span>
 764      <b class="header">Splats...</b>
 765      The JavaScript <b>arguments object</b> is a useful way to work with
 766      functions that accept variable numbers of arguments. CoffeeScript provides
 767      splats <code>...</code>, both for function definition as well as invocation,
 768      making variable numbers of arguments a little bit more palatable.
 769    </p>
 770    <div class='code'><pre><code>gold = silver = rest = <span class="string">"unknown"</span>
 771
 772<span class="function"><span class="title">awardMedals</span> = <span class="params">(first, second, others...)</span> -&gt;</span>
 773  gold   = first
 774  silver = second
 775  rest   = others
 776
 777contenders = [
 778  <span class="string">"Michael Phelps"</span>
 779  <span class="string">"Liu Xiang"</span>
 780  <span class="string">"Yao Ming"</span>
 781  <span class="string">"Allyson Felix"</span>
 782  <span class="string">"Shawn Johnson"</span>
 783  <span class="string">"Roman Sebrle"</span>
 784  <span class="string">"Guo Jingjing"</span>
 785  <span class="string">"Tyson Gay"</span>
 786  <span class="string">"Asafa Powell"</span>
 787  <span class="string">"Usain Bolt"</span>
 788]
 789
 790awardMedals contenders...
 791
 792alert <span class="string">"Gold: "</span> + gold
 793alert <span class="string">"Silver: "</span> + silver
 794alert <span class="string">"The Field: "</span> + rest
 795</code></pre><pre><code><span class="keyword">var</span> awardMedals, contenders, gold, rest, silver,
 796  slice = [].slice;
 797
 798gold = silver = rest = <span class="string">"unknown"</span>;
 799
 800awardMedals = <span class="function"><span class="keyword">function</span><span class="params">()</span> {</span>
 801  <span class="keyword">var</span> first, others, second;
 802  first = <span class="built_in">arguments</span>[<span class="number">0</span>], second = <span class="built_in">arguments</span>[<span class="number">1</span>], others = <span class="number">3</span> &lt;= <span class="built_in">arguments</span>.length ? slice.call(<span class="built_in">arguments</span>, <span class="number">2</span>) : [];
 803  gold = first;
 804  silver = second;
 805  <span class="keyword">return</span> rest = others;
 806};
 807
 808contenders = [<span class="string">"Michael Phelps"</span>, <span class="string">"Liu Xiang"</span>, <span class="string">"Yao Ming"</span>, <span class="string">"Allyson Felix"</span>, <span class="string">"Shawn Johnson"</span>, <span class="string">"Roman Sebrle"</span>, <span class="string">"Guo Jingjing"</span>, <span class="string">"Tyson Gay"</span>, <span class="string">"Asafa Powell"</span>, <span class="string">"Usain Bolt"</span>];
 809
 810awardMedals.apply(<span class="literal">null</span>, contenders);
 811
 812alert(<span class="string">"Gold: "</span> + gold);
 813
 814alert(<span class="string">"Silver: "</span> + silver);
 815
 816alert(<span class="string">"The Field: "</span> + rest);
 817</code></pre><script>window.example8 = "gold = silver = rest = \"unknown\"\n\nawardMedals = (first, second, others...) ->\n  gold   = first\n  silver = second\n  rest   = others\n\ncontenders = [\n  \"Michael Phelps\"\n  \"Liu Xiang\"\n  \"Yao Ming\"\n  \"Allyson Felix\"\n  \"Shawn Johnson\"\n  \"Roman Sebrle\"\n  \"Guo Jingjing\"\n  \"Tyson Gay\"\n  \"Asafa Powell\"\n  \"Usain Bolt\"\n]\n\nawardMedals contenders...\n\nalert \"Gold: \" + gold\nalert \"Silver: \" + silver\nalert \"The Field: \" + rest\n"</script><div class='minibutton load' onclick='javascript: loadConsole(example8);'>load</div><div class='minibutton ok' onclick='javascript: var awardMedals, contenders, gold, rest, silver,
 818  slice = [].slice;
 819
 820gold = silver = rest = "unknown";
 821
 822awardMedals = function() {
 823  var first, others, second;
 824  first = arguments[0], second = arguments[1], others = 3 <= arguments.length ? slice.call(arguments, 2) : [];
 825  gold = first;
 826  silver = second;
 827  return rest = others;
 828};
 829
 830contenders = ["Michael Phelps", "Liu Xiang", "Yao Ming", "Allyson Felix", "Shawn Johnson", "Roman Sebrle", "Guo Jingjing", "Tyson Gay", "Asafa Powell", "Usain Bolt"];
 831
 832awardMedals.apply(null, contenders);
 833
 834alert("Gold: " + gold);
 835
 836alert("Silver: " + silver);
 837
 838alert("The Field: " + rest);
 839;'>run</div><br class='clear' /></div>
 840
 841    <p>
 842      <span id="loops" class="bookmark"></span>
 843      <b class="header">Loops and Comprehensions</b>
 844      Most of the loops you'll write in CoffeeScript will be <b>comprehensions</b>
 845      over arrays, objects, and ranges. Comprehensions replace (and compile into)
 846      <b>for</b> loops, with optional guard clauses and the value of the current array index.
 847      Unlike for loops, array comprehensions are expressions, and can be returned
 848      and assigned.
 849    </p>
 850    <div class='code'><pre><code><span class="comment"># Eat lunch.</span>
 851eat food <span class="keyword">for</span> food <span class="keyword">in</span> [<span class="string">'toast'</span>, <span class="string">'cheese'</span>, <span class="string">'wine'</span>]
 852
 853<span class="comment"># Fine five course dining.</span>
 854courses = [<span class="string">'greens'</span>, <span class="string">'caviar'</span>, <span class="string">'truffles'</span>, <span class="string">'roast'</span>, <span class="string">'cake'</span>]
 855menu i + <span class="number">1</span>, dish <span class="keyword">for</span> dish, i <span class="keyword">in</span> courses
 856
 857<span class="comment"># Health conscious meal.</span>
 858foods = [<span class="string">'broccoli'</span>, <span class="string">'spinach'</span>, <span class="string">'chocolate'</span>]
 859eat food <span class="keyword">for</span> food <span class="keyword">in</span> foods <span class="keyword">when</span> food <span class="keyword">isnt</span> <span class="string">'chocolate'</span>
 860</code></pre><pre><code><span class="keyword">var</span> courses, dish, food, foods, i, j, k, l, len, len1, len2, ref;
 861
 862ref = [<span class="string">'toast'</span>, <span class="string">'cheese'</span>, <span class="string">'wine'</span>];
 863<span class="keyword">for</span> (j = <span class="number">0</span>, len = ref.length; j &lt; len; j++) {
 864  food = ref[j];
 865  eat(food);
 866}
 867
 868courses = [<span class="string">'greens'</span>, <span class="string">'caviar'</span>, <span class="string">'truffles'</span>, <span class="string">'roast'</span>, <span class="string">'cake'</span>];
 869
 870<span class="keyword">for</span> (i = k = <span class="number">0</span>, len1 = courses.length; k &lt; len1; i = ++k) {
 871  dish = courses[i];
 872  menu(i + <span class="number">1</span>, dish);
 873}
 874
 875foods = [<span class="string">'broccoli'</span>, <span class="string">'spinach'</span>, <span class="string">'chocolate'</span>];
 876
 877<span class="keyword">for</span> (l = <span class="number">0</span>, len2 = foods.length; l &lt; len2; l++) {
 878  food = foods[l];
 879  <span class="keyword">if</span> (food !== <span class="string">'chocolate'</span>) {
 880    eat(food);
 881  }
 882}
 883</code></pre><script>window.example9 = "# Eat lunch.\neat food for food in ['toast', 'cheese', 'wine']\n\n# Fine five course dining.\ncourses = ['greens', 'caviar', 'truffles', 'roast', 'cake']\nmenu i + 1, dish for dish, i in courses\n\n# Health conscious meal.\nfoods = ['broccoli', 'spinach', 'chocolate']\neat food for food in foods when food isnt 'chocolate'\n"</script><div class='minibutton load' onclick='javascript: loadConsole(example9);'>load</div><br class='clear' /></div>
 884    <p>
 885      Comprehensions should be able to handle most places where you otherwise
 886      would use a loop, <b>each</b>/<b>forEach</b>, <b>map</b>, or <b>select</b>/<b>filter</b>, for example:
 887      <code>shortNames = (name for name in list when name.length &lt; 5)</code><br />
 888      If you know the start and end of your loop, or would like to step through
 889      in fixed-size increments, you can use a range to specify the start and
 890      end of your comprehension.
 891    </p>
 892    <div class='code'><pre><code>countdown = (num <span class="keyword">for</span> num <span class="keyword">in</span> [<span class="number">10.</span><span class="number">.1</span>])
 893</code></pre><pre><code><span class="keyword">var</span> countdown, num;
 894
 895countdown = (<span class="function"><span class="keyword">function</span><span class="params">()</span> {</span>
 896  <span class="keyword">var</span> i, results;
 897  results = [];
 898  <span class="keyword">for</span> (num = i = <span class="number">10</span>; i &gt;= <span class="number">1</span>; num = --i) {
 899    results.push(num);
 900  }
 901  <span class="keyword">return</span> results;
 902})();
 903</code></pre><script>window.example10 = "countdown = (num for num in [10..1])\n"</script><div class='minibutton load' onclick='javascript: loadConsole(example10);'>load</div><div class='minibutton ok' onclick='javascript: var countdown, num;
 904
 905countdown = (function() {
 906  var i, results;
 907  results = [];
 908  for (num = i = 10; i >= 1; num = --i) {
 909    results.push(num);
 910  }
 911  return results;
 912})();
 913;alert(countdown);'>run: countdown</div><br class='clear' /></div>
 914    <p>
 915      Note how because we are assigning the value of the comprehensions to a
 916      variable in the example above, CoffeeScript is collecting the result of
 917      each iteration into an array. Sometimes functions end with loops that are
 918      intended to run only for their side-effects. Be careful that you're not
 919      accidentally returning the results of the comprehension in these cases,
 920      by adding a meaningful return value &mdash; like <code>true</code> &mdash; or <code>null</code>,
 921      to the bottom of your function.
 922    </p>
 923    <p>
 924      To step through a range comprehension in fixed-size chunks,
 925      use <code>by</code>, for example:<br />
 926      <code>evens = (x for x in [0..10] by 2)</code>
 927    </p>
 928    <p>
 929      If you don't need the current iteration value you may omit it:<br />
 930      <code>browser.closeCurrentTab() for [0...count]</code>
 931    </p>
 932    <p>
 933      Comprehensions can also be used to iterate over the keys and values in
 934      an object. Use <code>of</code> to signal comprehension over the properties of
 935      an object instead of the values in an array.
 936    </p>
 937    <div class='code'><pre><code>yearsOld = <span class="attribute">max</span>: <span class="number">10</span>, <span class="attribute">ida</span>: <span class="number">9</span>, <span class="attribute">tim</span>: <span class="number">11</span>
 938
 939ages = <span class="keyword">for</span> child, age <span class="keyword">of</span> yearsOld
 940  <span class="string">"<span class="subst">#{child}</span> is <span class="subst">#{age}</span>"</span>
 941</code></pre><pre><code><span class="keyword">var</span> age, ages, child, yearsOld;
 942
 943yearsOld = {
 944  max: <span class="number">10</span>,
 945  ida: <span class="number">9</span>,
 946  tim: <span class="number">11</span>
 947};
 948
 949ages = (<span class="function"><span class="keyword">function</span><span class="params">()</span> {</span>
 950  <span class="keyword">var</span> results;
 951  results = [];
 952  <span class="keyword">for</span> (child <span class="keyword">in</span> yearsOld) {
 953    age = yearsOld[child];
 954    results.push(child + <span class="string">" is "</span> + age);
 955  }
 956  <span class="keyword">return</span> results;
 957})();
 958</code></pre><script>window.example11 = "yearsOld = max: 10, ida: 9, tim: 11\n\nages = for child, age of yearsOld\n  \"#{child} is #{age}\"\n"</script><div class='minibutton load' onclick='javascript: loadConsole(example11);'>load</div><div class='minibutton ok' onclick='javascript: var age, ages, child, yearsOld;
 959
 960yearsOld = {
 961  max: 10,
 962  ida: 9,
 963  tim: 11
 964};
 965
 966ages = (function() {
 967  var results;
 968  results = [];
 969  for (child in yearsOld) {
 970    age = yearsOld[child];
 971    results.push(child + " is " + age);
 972  }
 973  return results;
 974})();
 975;alert(ages.join(", "));'>run: ages.join(", ")</div><br class='clear' /></div>
 976    <p>
 977      If you would like to iterate over just the keys that are defined on the
 978      object itself, by adding a <code>hasOwnProperty</code>
 979      check to avoid properties that may be inherited from the prototype, use<br />
 980      <code>for own key, value of object</code>
 981    </p>
 982    <p>
 983      The only low-level loop that CoffeeScript provides is the <b>while</b> loop. The
 984      main difference from JavaScript is that the <b>while</b> loop can be used
 985      as an expression, returning an array containing the result of each iteration
 986      through the loop.
 987    </p>
 988    <div class='code'><pre><code><span class="comment"># Econ 101</span>
 989<span class="keyword">if</span> <span class="keyword">this</span>.studyingEconomics
 990  buy()  <span class="keyword">while</span> supply &gt; demand
 991  sell() <span class="keyword">until</span> supply &gt; demand
 992
 993<span class="comment"># Nursery Rhyme</span>
 994num = <span class="number">6</span>
 995lyrics = <span class="keyword">while</span> num -= <span class="number">1</span>
 996  <span class="string">"<span class="subst">#{num}</span> little monkeys, jumping on the bed.
 997    One fell out and bumped his head."</span>
 998</code></pre><pre><code><span class="keyword">var</span> lyrics, num;
 999
1000<span class="keyword">if</span> (<span class="keyword">this</span>.studyingEconomics) {
1001  <span class="keyword">while</span> (supply &gt; demand) {
1002    buy();
1003  }
1004  <span class="keyword">while</span> (!(supply &gt; demand)) {
1005    sell();
1006  }
1007}
1008
1009num = <span class="number">6</span>;
1010
1011lyrics = (<span class="function"><span class="keyword">function</span><span class="params">()</span> {</span>
1012  <span class="keyword">var</span> results;
1013  results = [];
1014  <span class="keyword">while</span> (num -= <span class="number">1</span>) {
1015    results.push(num + <span class="string">" little monkeys, jumping on the bed. One fell out and bumped his head."</span>);
1016  }
1017  <span class="keyword">return</span> results;
1018})();
1019</code></pre><script>window.example12 = "# Econ 101\nif this.studyingEconomics\n  buy()  while supply > demand\n  sell() until supply > demand\n\n# Nursery Rhyme\nnum = 6\nlyrics = while num -= 1\n  \"#{num} little monkeys, jumping on the bed.\n    One fell out and bumped his head.\"\n"</script><div class='minibutton load' onclick='javascript: loadConsole(example12);'>load</div><div class='minibutton ok' onclick='javascript: var lyrics, num;
1020
1021if (this.studyingEconomics) {
1022  while (supply > demand) {
1023    buy();
1024  }
1025  while (!(supply > demand)) {
1026    sell();
1027  }
1028}
1029
1030num = 6;
1031
1032lyrics = (function() {
1033  var results;
1034  results = [];
1035  while (num -= 1) {
1036    results.push(num + " little monkeys, jumping on the bed. One fell out and bumped his head.");
1037  }
1038  return results;
1039})();
1040;alert(lyrics.join("
1041"));'>run: lyrics.join("
1042")</div><br class='clear' /></div>
1043    <p>
1044      For readability, the <b>until</b> keyword is equivalent to <code>while not</code>,
1045      and the <b>loop</b> keyword is equivalent to <code>while true</code>.
1046    </p>
1047    <p>
1048      When using a JavaScript loop to generate functions, it's common to insert
1049      a closure wrapper in order to ensure that loop variables are closed over,
1050      and all the generated functions don't just share the final values. CoffeeScript
1051      provides the <code>do</code> keyword, which immediately invokes a passed function,
1052      forwarding any arguments.
1053    </p>
1054    <div class='code'><pre><code><span class="keyword">for</span> filename <span class="keyword">in</span> list
1055  <span class="keyword">do</span> <span class="function"><span class="params">(filename)</span> -&gt;</span>
1056    fs.readFile filename, <span class="function"><span class="params">(err, contents)</span> -&gt;</span>
1057      compile filename, contents.toString()</code></pre><pre><code><span class="keyword">var</span> filename, fn, i, len;
1058
1059fn = <span class="function"><span class="keyword">function</span><span class="params">(filename)</span> {</span>
1060  <span class="keyword">return</span> fs.readFile(filename, <span class="function"><span class="keyword">function</span><span class="params">(err, contents)</span> {</span>
1061    <span class="keyword">return</span> compile(filename, contents.toString());
1062  });
1063};
1064<span class="keyword">for</span> (i = <span class="number">0</span>, len = list.length; i &lt; len; i++) {
1065  filename = list[i];
1066  fn(filename);
1067}
1068</code></pre><script>window.example13 = "for filename in list\n  do (filename) ->\n    fs.readFile filename, (err, contents) ->\n      compile filename, contents.toString()"</script><div class='minibutton load' onclick='javascript: loadConsole(example13);'>load</div><br class='clear' /></div>
1069
1070    <p>
1071      <span id="slices" class="bookmark"></span>
1072      <b class="header">Array Slicing and Splicing with Ranges</b>
1073      Ranges can also be used to extract slices of arrays.
1074      With two dots (<code>3..6</code>), the range is inclusive (<code>3, 4, 5, 6</code>);
1075      with three dots (<code>3...6</code>), the range excludes the end (<code>3, 4, 5</code>).
1076      Slices indices have useful defaults. An omitted first index defaults to
1077      zero and an omitted second index defaults to the size of the array.
1078    </p>
1079    <div class='code'><pre><code>numbers = [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>, <span class="number">6</span>, <span class="number">7</span>, <span class="number">8</span>, <span class="number">9</span>]
1080
1081start   = numbers[<span class="number">0.</span><span class="number">.2</span>]
1082
1083middle  = numbers[<span class="number">3.</span>..-<span class="number">2</span>]
1084
1085end     = numbers[-<span class="number">2.</span>.]
1086
1087copy    = numbers[..]
1088</code></pre><pre><code><span class="keyword">var</span> copy, end, middle, numbers, start;
1089
1090numbers = [<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>];
1091
1092start = numbers.slice(<span class="number">0</span…

Large files files are truncated, but you can click here to view the full file