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