PageRenderTime 73ms CodeModel.GetById 18ms RepoModel.GetById 0ms 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
  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>, <span class="number">3</span>);
  952. middle = numbers.slice(<span class="number">3</span>, -<span class="number">2</span>);
  953. end = numbers.slice(-<span class="number">2</span>);
  954. copy = numbers.slice(<span class="number">0</span>);
  955. </code></pre><script>window.example14 = "numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]\n\nstart = numbers[0..2]\n\nmiddle = numbers[3...-2]\n\nend = numbers[-2..]\n\ncopy = numbers[..]\n"</script><div class='minibutton load' onclick='javascript: loadConsole(example14);'>load</div><div class='minibutton ok' onclick='javascript: var copy, end, middle, numbers, start;
  956. numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];
  957. start = numbers.slice(0, 3);
  958. middle = numbers.slice(3, -2);
  959. end = numbers.slice(-2);
  960. copy = numbers.slice(0);
  961. ;alert(middle);'>run: middle</div><br class='clear' /></div>
  962. <p>
  963. The same syntax can be used with assignment to replace a segment of an array
  964. with new values, splicing it.
  965. </p>
  966. <div class='code'><pre><code>numbers = [<span class="number">0</span>, <span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>, <span class="number">6</span>, <span class="number">7</span>, <span class="number">8</span>, <span class="number">9</span>]
  967. numbers[<span class="number">3.</span><span class="number">.6</span>] = [-<span class="number">3</span>, -<span class="number">4</span>, -<span class="number">5</span>, -<span class="number">6</span>]
  968. </code></pre><pre><code><span class="keyword">var</span> numbers, ref;
  969. numbers = [<span class="number">0</span>, <span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>, <span class="number">6</span>, <span class="number">7</span>, <span class="number">8</span>, <span class="number">9</span>];
  970. [].splice.apply(numbers, [<span class="number">3</span>, <span class="number">4</span>].concat(ref = [-<span class="number">3</span>, -<span class="number">4</span>, -<span class="number">5</span>, -<span class="number">6</span>])), ref;
  971. </code></pre><script>window.example15 = "numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n\nnumbers[3..6] = [-3, -4, -5, -6]\n"</script><div class='minibutton load' onclick='javascript: loadConsole(example15);'>load</div><div class='minibutton ok' onclick='javascript: var numbers, ref;
  972. numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
  973. [].splice.apply(numbers, [3, 4].concat(ref = [-3, -4, -5, -6])), ref;
  974. ;alert(numbers);'>run: numbers</div><br class='clear' /></div>
  975. <p>
  976. Note that JavaScript strings are immutable, and can't be spliced.
  977. </p>
  978. <p>
  979. <span id="expressions" class="bookmark"></span>
  980. <b class="header">Everything is an Expression (at least, as much as possible)</b>
  981. You might have noticed how even though we don't add return statements
  982. to CoffeeScript functions, they nonetheless return their final value.
  983. The CoffeeScript compiler tries to make sure that all statements in the
  984. language can be used as expressions. Watch how the <code>return</code> gets
  985. pushed down into each possible branch of execution in the function
  986. below.
  987. </p>
  988. <div class='code'><pre><code><span class="function"><span class="title">grade</span> = <span class="params">(student)</span> -&gt;</span>
  989. <span class="keyword">if</span> student.excellentWork
  990. <span class="string">"A+"</span>
  991. <span class="keyword">else</span> <span class="keyword">if</span> student.okayStuff
  992. <span class="keyword">if</span> student.triedHard <span class="keyword">then</span> <span class="string">"B"</span> <span class="keyword">else</span> <span class="string">"B-"</span>
  993. <span class="keyword">else</span>
  994. <span class="string">"C"</span>
  995. eldest = <span class="keyword">if</span> <span class="number">24</span> &gt; <span class="number">21</span> <span class="keyword">then</span> <span class="string">"Liz"</span> <span class="keyword">else</span> <span class="string">"Ike"</span></code></pre><pre><code><span class="keyword">var</span> eldest, grade;
  996. grade = <span class="function"><span class="keyword">function</span><span class="params">(student)</span> {</span>
  997. <span class="keyword">if</span> (student.excellentWork) {
  998. <span class="keyword">return</span> <span class="string">"A+"</span>;
  999. } <span class="keyword">else</span> <span class="keyword">if</span> (student.okayStuff) {
  1000. <span class="keyword">if</span> (student.triedHard) {
  1001. <span class="keyword">return</span> <span class="string">"B"</span>;
  1002. } <span class="keyword">else</span> {
  1003. <span class="keyword">return</span> <span class="string">"B-"</span>;
  1004. }
  1005. } <span class="keyword">else</span> {
  1006. <span class="keyword">return</span> <span class="string">"C"</span>;
  1007. }
  1008. };
  1009. eldest = <span class="number">24</span> &gt; <span class="number">21</span> ? <span class="string">"Liz"</span> : <span class="string">"Ike"</span>;
  1010. </code></pre><script>window.example16 = "grade = (student) ->\n if student.excellentWork\n \"A+\"\n else if student.okayStuff\n if student.triedHard then \"B\" else \"B-\"\n else\n \"C\"\n\neldest = if 24 > 21 then \"Liz\" else \"Ike\""</script><div class='minibutton load' onclick='javascript: loadConsole(example16);'>load</div><div class='minibutton ok' onclick='javascript: var eldest, grade;
  1011. grade = function(student) {
  1012. if (student.excellentWork) {
  1013. return "A+";
  1014. } else if (student.okayStuff) {
  1015. if (student.triedHard) {
  1016. return "B";
  1017. } else {
  1018. return "B-";
  1019. }
  1020. } else {
  1021. return "C";
  1022. }
  1023. };
  1024. eldest = 24 > 21 ? "Liz" : "Ike";
  1025. ;alert(eldest);'>run: eldest</div><br class='clear' /></div>
  1026. <p>
  1027. Even though functions will always return their final value, it's both possible
  1028. and encouraged to return early from a function body writing out the explicit
  1029. return (<code>return value</code>), when you know that you're done.
  1030. </p>
  1031. <p>
  1032. Because variable declarations occur at the top of scope, assignment can
  1033. be used within expressions, even for variables that haven't been seen before:
  1034. </p>
  1035. <div class='code'><pre><code>six = (one = <span class="number">1</span>) + (two = <span class="number">2</span>) + (three = <span class="number">3</span>)
  1036. </code></pre><pre><code><span class="keyword">var</span> one, six, three, two;
  1037. six = (one = <span class="number">1</span>) + (two = <span class="number">2</span>) + (three = <span class="number">3</span>);
  1038. </code></pre><script>window.example17 = "six = (one = 1) + (two = 2) + (three = 3)\n"</script><div class='minibutton load' onclick='javascript: loadConsole(example17);'>load</div><div class='minibutton ok' onclick='javascript: var one, six, three, two;
  1039. six = (one = 1) + (two = 2) + (three = 3);
  1040. ;alert(six);'>run: six</div><br class='clear' /></div>
  1041. <p>
  1042. Things that would otherwise be statements in JavaScript, when used
  1043. as part of an expression in CoffeeScript, are converted into expressions
  1044. by wrapping them in a closure. This lets you do useful things, like assign
  1045. the result of a comprehension to a variable:
  1046. </p>
  1047. <div class='code'><pre><code><span class="comment"># The first ten global properties.</span>
  1048. globals = (name <span class="keyword">for</span> name <span class="keyword">of</span> <span class="built_in">window</span>)[<span class="number">0.</span>.<span class="number">.10</span>]</code></pre><pre><code><span class="keyword">var</span> globals, name;
  1049. globals = ((<span class="function"><span class="keyword">function</span><span class="params">()</span> {</span>
  1050. <span class="keyword">var</span> results;
  1051. results = [];
  1052. <span class="keyword">for</span> (name <span class="keyword">in</span> window) {
  1053. results.push(name);
  1054. }
  1055. <span class="keyword">return</span> results;
  1056. })()).slice(<span class="number">0</span>, <span class="number">10</span>);
  1057. </code></pre><script>window.example18 = "# The first ten global properties.\n\nglobals = (name for name of window)[0...10]"</script><div class='minibutton load' onclick='javascript: loadConsole(example18);'>load</div><div class='minibutton ok' onclick='javascript: var globals, name;
  1058. globals = ((function() {
  1059. var results;
  1060. results = [];
  1061. for (name in window) {
  1062. results.push(name);
  1063. }
  1064. return results;
  1065. })()).slice(0, 10);
  1066. ;alert(globals);'>run: globals</div><br class='clear' /></div>
  1067. <p>
  1068. As well as silly things, like passing a <b>try/catch</b> statement directly
  1069. into a function call:
  1070. </p>
  1071. <div class='code'><pre><code>alert(
  1072. <span class="keyword">try</span>
  1073. nonexistent / <span class="literal">undefined</span>
  1074. <span class="keyword">catch</span> error
  1075. <span class="string">"And the error is ... <span class="subst">#{error}</span>"</span>
  1076. )
  1077. </code></pre><pre><code><span class="keyword">var</span> error;
  1078. alert((<span class="function"><span class="keyword">function</span><span class="params">()</span> {</span>
  1079. <span class="keyword">var</span> error1;
  1080. <span class="keyword">try</span> {
  1081. <span class="keyword">return</span> nonexistent / <span class="keyword">void</span> <span class="number">0</span>;
  1082. } <span class="keyword">catch</span> (error1) {
  1083. error = error1;
  1084. <span class="keyword">return</span> <span class="string">"And the error is ... "</span> + error;
  1085. }
  1086. })());
  1087. </code></pre><script>window.example19 = "alert(\n try\n nonexistent / undefined\n catch error\n \"And the error is ... #{error}\"\n)\n"</script><div class='minibutton load' onclick='javascript: loadConsole(example19);'>load</div><div class='minibutton ok' onclick='javascript: var error;
  1088. alert((function() {
  1089. var error1;
  1090. try {
  1091. return nonexistent / void 0;
  1092. } catch (error1) {
  1093. error = error1;
  1094. return "And the error is ... " + error;
  1095. }
  1096. })());
  1097. ;'>run</div><br class='clear' /></div>
  1098. <p>
  1099. There are a handful of statements in JavaScript that can't be meaningfully
  1100. converted into expressions, namely <code>break</code>, <code>continue</code>,
  1101. and <code>return</code>. If you make use of them within a block of code,
  1102. CoffeeScript won't try to perform the conversion.
  1103. </p>
  1104. <p>
  1105. <span id="operators" class="bookmark"></span>
  1106. <b class="header">Operators and Aliases</b>
  1107. Because the <code>==</code> operator frequently causes undesirable coercion,
  1108. is intransitive, and has a different meaning than in other languages,
  1109. CoffeeScript compiles <code>==</code> into <code>===</code>, and <code>!=</code> into
  1110. <code>!==</code>.
  1111. In addition, <code>is</code> compiles into <code>===</code>,
  1112. and <code>isnt</code> into <code>!==</code>.
  1113. </p>
  1114. <p>
  1115. You can use <code>not</code> as an alias for <code>!</code>.
  1116. </p>
  1117. <p>
  1118. For logic, <code>and</code> compiles to <code>&amp;&amp;</code>, and <code>or</code>
  1119. into <code>||</code>.
  1120. </p>
  1121. <p>
  1122. Instead of a newline or semicolon, <code>then</code> can be used to separate
  1123. conditions from expressions, in <b>while</b>,
  1124. <b>if</b>/<b>else</b>, and <b>switch</b>/<b>when</b> statements.
  1125. </p>
  1126. <p>
  1127. As in <a href="http://yaml.org/">YAML</a>, <code>on</code> and <code>yes</code>
  1128. are the same as boolean <code>true</code>, while <code>off</code> and <code>no</code> are boolean <code>false</code>.
  1129. </p>
  1130. <p>
  1131. <code>unless</code> can be used as the inverse of <code>if</code>.
  1132. </p>
  1133. <p>
  1134. As a shortcut for <code>this.property</code>, you can use <code>@property</code>.
  1135. </p>
  1136. <p>
  1137. You can use <code>in</code> to test for array presence, and <code>of</code> to
  1138. test for JavaScript object-key presence.
  1139. </p>
  1140. <p>
  1141. To simplify math expressions, <code>**</code> can be used for exponentiation
  1142. and <code>//</code> performs integer division. <code>%</code> works just like in
  1143. JavaScript, while <code>%%</code> provides
  1144. <a href="http://en.wikipedia.org/wiki/Modulo_operation">“dividend dependent modulo”</a>:
  1145. </p>
  1146. <div class='code'><pre><code>-<span class="number">7</span> % <span class="number">5</span> == -<span class="number">2</span> <span class="comment"># The remainder of 7 / 5</span>
  1147. -<span class="number">7</span> %% <span class="number">5</span> == <span class="number">3</span> <span class="comment"># n %% 5 is always between 0 and 4</span>
  1148. tabs.selectTabAtIndex((tabs.currentIndex - count) %% tabs.length)
  1149. </code></pre><pre><code><span class="keyword">var</span> modulo = <span class="function"><span class="keyword">function</span><span class="params">(a, b)</span> {</span> <span class="keyword">return</span> (+a % (b = +b) + b) % b; };
  1150. -<span class="number">7</span> % <span class="number">5</span> === -<span class="number">2</span>;
  1151. modulo(-<span class="number">7</span>, <span class="number">5</span>) === <span class="number">3</span>;
  1152. tabs.selectTabAtIndex(modulo(tabs.currentIndex - count, tabs.length));
  1153. </code></pre><script>window.example20 = "-7 % 5 == -2 # The remainder of 7 / 5\n-7 %% 5 == 3 # n %% 5 is always between 0 and 4\n\ntabs.selectTabAtIndex((tabs.currentIndex - count) %% tabs.length)\n"</script><div class='minibutton load' onclick='javascript: loadConsole(example20);'>load</div><br class='clear' /></div>
  1154. <p>
  1155. All together now:
  1156. </p>
  1157. <table class="definitions">
  1158. <tr><th>CoffeeScript</th><th>JavaScript</th></tr>
  1159. <tr><td><code>is</code></td><td><code>===</code></td></tr>
  1160. <tr><td><code>isnt</code></td><td><code>!==</code></td></tr>
  1161. <tr><td><code>not</code></td><td><code>!</code></td></tr>
  1162. <tr><td><code>and</code></td><td><code>&amp;&amp;</code></td></tr>
  1163. <tr><td><code>or</code></td><td><code>||</code></td></tr>
  1164. <tr><td><code>true</code>, <code>yes</code>, <code>on</code></td><td><code>true</code></td></tr>
  1165. <tr><td><code>false</code>, <code>no</code>, <code>off</code></td><td><code>false</code></td></tr>
  1166. <tr><td><code>@</code>, <code>this</code></td><td><code>this</code></td></tr>
  1167. <tr><td><code>of</code></td><td><code>in</code></td></tr>
  1168. <tr><td><code>in</code></td><td><i><small>no JS equivalent</small></i></td></tr>
  1169. <tr><td><code>a ** b</code></td><td><code>Math.pow(a, b)</code></td></tr>
  1170. <tr><td><code>a // b</code></td><td><code>Math.floor(a / b)</code></td></tr>
  1171. <tr><td><code>a %% b</code></td><td><code>(a % b + b) % b</code></td></tr>
  1172. </table>
  1173. <div class='code'><pre><code>launch() <span class="keyword">if</span> ignition <span class="keyword">is</span> <span class="literal">on</span>
  1174. volume = <span class="number">10</span> <span class="keyword">if</span> band <span class="keyword">isnt</span> SpinalTap
  1175. letTheWildRumpusBegin() <span class="keyword">unless</span> answer <span class="keyword">is</span> <span class="literal">no</span>
  1176. <span class="keyword">if</span> car.speed &lt; limit <span class="keyword">then</span> accelerate()
  1177. winner = <span class="literal">yes</span> <span class="keyword">if</span> pick <span class="keyword">in</span> [<span class="number">47</span>, <span class="number">92</span>, <span class="number">13</span>]
  1178. <span class="built_in">print</span> inspect <span class="string">"My name is <span class="subst">#{<span class="property">@name</span>}</span>"</span>
  1179. </code></pre><pre><code><span class="keyword">var</span> volume, winner;
  1180. <span class="keyword">if</span> (ignition === <span class="literal">true</span>) {
  1181. launch();
  1182. }
  1183. <span class="keyword">if</span> (band !== SpinalTap) {
  1184. volume = <span class="number">10</span>;
  1185. }
  1186. <span class="keyword">if</span> (answer !== <span class="literal">false</span>) {
  1187. letTheWildRumpusBegin();
  1188. }
  1189. <span class="keyword">if</span> (car.speed &lt; limit) {
  1190. accelerate();
  1191. }
  1192. <span class="keyword">if</span> (pick === <span class="number">47</span> || pick === <span class="number">92</span> || pick === <span class="number">13</span>) {
  1193. winner = <span class="literal">true</span>;
  1194. }
  1195. print(inspect(<span class="string">"My name is "</span> + <span class="keyword">this</span>.name));
  1196. </code></pre><script>window.example21 = "launch() if ignition is on\n\nvolume = 10 if band isnt SpinalTap\n\nletTheWildRumpusBegin() unless answer is no\n\nif car.speed < limit then accelerate()\n\nwinner = yes if pick in [47, 92, 13]\n\nprint inspect \"My name is #{@name}\"\n"</script><div class='minibutton load' onclick='javascript: loadConsole(example21);'>load</div><br class='clear' /></div>
  1197. <p>
  1198. <b class="header">The Existential Operator</b>
  1199. It's a little difficult to check for the existence of a variable in
  1200. JavaScript. <code>if (variable) ...</code> comes close, but fails for zero,
  1201. the empty string, and false. CoffeeScript's existential operator <code>?</code> returns true unless
  1202. a variable is <b>null</b> or <b>undefined</b>, which makes it analogous
  1203. to Ruby's <code>nil?</code>
  1204. </p>
  1205. <p>
  1206. It can also be used for safer conditional assignment than <code>||=</code>
  1207. provides, for cases where you may be handling numbers or strings.
  1208. </p>
  1209. <div class='code'><pre><code>solipsism = <span class="literal">true</span> <span class="keyword">if</span> mind? <span class="keyword">and</span> <span class="keyword">not</span> world?
  1210. speed = <span class="number">0</span>
  1211. speed ?= <span class="number">15</span>
  1212. footprints = yeti ? <span class="string">"bear"</span>
  1213. </code></pre><pre><code><span class="keyword">var</span> footprints, solipsism, speed;
  1214. <span class="keyword">if</span> ((<span class="keyword">typeof</span> mind !== <span class="string">"undefined"</span> &amp;&amp; mind !== <span class="literal">null</span>) &amp;&amp; (<span class="keyword">typeof</span> world === <span class="string">"undefined"</span> || world === <span class="literal">null</span>)) {
  1215. solipsism = <span class="literal">true</span>;
  1216. }
  1217. speed = <span class="number">0</span>;
  1218. <span class="keyword">if</span> (speed == <span class="literal">null</span>) {
  1219. speed = <span class="number">15</span>;
  1220. }
  1221. footprints = <span class="keyword">typeof</span> yeti !== <span class="string">"undefined"</span> &amp;&amp; yeti !== <span class="literal">null</span> ? yeti : <span class="string">"bear"</span>;
  1222. </code></pre><script>window.example22 = "solipsism = true if mind? and not world?\n\nspeed = 0\nspeed ?= 15\n\nfootprints = yeti ? \"bear\"\n"</script><div class='minibutton load' onclick='javascript: loadConsole(example22);'>load</div><div class='minibutton ok' onclick='javascript: var footprints, solipsism, speed;
  1223. if ((typeof mind !== "undefined" && mind !== null) && (typeof world === "undefined" || world === null)) {
  1224. solipsism = true;
  1225. }
  1226. speed = 0;
  1227. if (speed == null) {
  1228. speed = 15;
  1229. }
  1230. footprints = typeof yeti !== "undefined" && yeti !== null ? yeti : "bear";
  1231. ;alert(footprints);'>run: footprints</div><br class='clear' /></div>
  1232. <p>
  1233. The accessor variant of the existential operator <code>?.</code> can be used to soak
  1234. up null references in a chain of properties. Use it instead
  1235. of the dot accessor <code>.</code> in cases where the base value may be <b>null</b>
  1236. or <b>undefined</b>. If all of the properties exist then you'll get the expected
  1237. result, if the chain is broken, <b>undefined</b> is returned instead of
  1238. the <b>TypeError</b> that would be raised otherwise.
  1239. </p>
  1240. <div class='code'><pre><code>zip = lottery.drawWinner?().address?.zipcode
  1241. </code></pre><pre><code><span class="keyword">var</span> ref, zip;
  1242. zip = <span class="keyword">typeof</span> lottery.drawWinner === <span class="string">"function"</span> ? (ref = lottery.drawWinner().address) != <span class="literal">null</span> ? ref.zipcode : <span class="keyword">void</span> <span class="number">0</span> : <span class="keyword">void</span> <span class="number">0</span>;
  1243. </code></pre><script>window.example23 = "zip = lottery.drawWinner?().address?.zipcode\n"</script><div class='minibutton load' onclick='javascript: loadConsole(example23);'>load</div><br class='clear' /></div>
  1244. <p>
  1245. Soaking up nulls is similar to Ruby's
  1246. <a href="https://rubygems.org/gems/andand">andand gem</a>, and to the
  1247. <a href="http://groovy.codehaus.org/Operators#Operators-SafeNavigationOperator%28%3F.%29">safe navigation operator</a>
  1248. in Groovy.
  1249. </p>
  1250. <p>
  1251. <span id="classes" class="bookmark"></span>
  1252. <b class="header">Classes, Inheritance, and Super</b>
  1253. JavaScript's prototypal inheritance has always been a bit of a
  1254. brain-bender, with a whole family tree of libraries that provide a cleaner
  1255. syntax for classical inheritance on top of JavaScript's prototypes:
  1256. <a href="http://code.google.com/p/base2/">Base2</a>,
  1257. <a href="http://prototypejs.org/">Prototype.js</a>,
  1258. <a href="http://jsclass.jcoglan.com/">JS.Class</a>, etc.
  1259. The libraries provide syntactic sugar, but the built-in inheritance would
  1260. be completely usable if it weren't for a couple of small exceptions:
  1261. it's awkward to call <b>super</b> (the prototype object's
  1262. implementation of the current function), and it's awkward to correctly
  1263. set the prototype chain.
  1264. </p>
  1265. <p>
  1266. Instead of repetitively attaching functions to a prototype, CoffeeScript
  1267. provides a basic <code>class</code> structure that allows you to name your class,
  1268. set the superclass, assign prototypal properties, and define the constructor,
  1269. in a single assignable expression.
  1270. </p>
  1271. <p>
  1272. Constructor functions are named, to better support helpful stack traces.
  1273. In the first class in the example below, <code>this.constructor.name is "Animal"</code>.
  1274. </p>
  1275. <div class='code'><pre><code><span class="class"><span class="keyword">class</span> <span class="title">Animal</span></span>
  1276. <span class="attribute">constructor</span>: <span class="function"><span class="params">(<span class="property">@name</span>)</span> -&gt;</span>
  1277. <span class="attribute">move</span>: <span class="function"><span class="params">(meters)</span> -&gt;</span>
  1278. alert <span class="property">@name</span> + <span class="string">" moved <span class="subst">#{meters}</span>m."</span>
  1279. <span class="class"><span class="keyword">class</span> <span class="title">Snake</span> <span class="keyword">extends</span> <span class="title">Animal</span></span>
  1280. <span class="attribute">move</span>:<span class="function"> -&gt;</span>
  1281. alert <span class="string">"Slithering..."</span>
  1282. <span class="keyword">super</span> <span class="number">5</span>
  1283. <span class="class"><span class="keyword">class</span> <span class="title">Horse</span> <span class="keyword">extends</span> <span class="title">Animal</span></span>
  1284. <span class="attribute">move</span>:<span class="function"> -&gt;</span>
  1285. alert <span class="string">"Galloping..."</span>
  1286. <span class="keyword">super</span> <span class="number">45</span>
  1287. sam = <span class="keyword">new</span> Snake <span class="string">"Sammy the Python"</span>
  1288. tom = <span class="keyword">new</span> Horse <span class="string">"Tommy the Palomino"</span>
  1289. sam.move()
  1290. tom.move()
  1291. </code></pre><pre><code><span class="keyword">var</span> Animal, Horse, Snake, sam, tom,
  1292. extend = <span class="function"><span class="keyword">function</span><span class="params">(child, parent)</span> {</span> <span class="keyword">for</span> (<span class="keyword">var</span> key <span class="keyword">in</span> parent) { <span class="keyword">if</span> (hasProp.call(parent, key)) child[key] = parent[key]; } <span class="function"><span class="keyword">function</span> <span class="title">ctor</span><span class="params">()</span> {</span> <span class="keyword">this</span>.constructor = child; } ctor.prototype = parent.prototype; child.prototype = <span class="keyword">new</span> ctor(); child.__super__ = parent.prototype; <span class="keyword">return</span> child; },
  1293. hasProp = {}.hasOwnProperty;
  1294. Animal = (<span class="function"><span class="keyword">function</span><span class="params">()</span> {</span>
  1295. <span class="function"><span class="keyword">function</span> <span class="title">Animal</span><span class="params">(name)</span> {</span>
  1296. <span class="keyword">this</span>.name = name;
  1297. }
  1298. Animal.prototype.move = <span class="function"><span class="keyword">function</span><span class="params">(meters)</span> {</span>
  1299. <span class="keyword">return</span> alert(<span class="keyword">this</span>.name + (<span class="string">" moved "</span> + meters + <span class="string">"m."</span>));
  1300. };
  1301. <span class="keyword">return</span> Animal;
  1302. })();
  1303. Snake = (<span class="function"><span class="keyword">function</span><span class="params">(superClass)</span> {</span>
  1304. extend(Snake, superClass);
  1305. <span class="function"><span class="keyword">function</span> <span class="title">Snake</span><span class="params">()</span> {</span>
  1306. <span class="keyword">return</span> Snake.__super__.constructor.apply(<span class="keyword">this</span>, <span class="built_in">arguments</span>);
  1307. }
  1308. Snake.prototype.move = <span class="function"><span class="keyword">function</span><span class="params">()</span> {</span>
  1309. alert(<span class="string">"Slithering..."</span>);
  1310. <span class="keyword">return</span> Snake.__super__.move.call(<span class="keyword">this</span>, <span class="number">5</span>);
  1311. };
  1312. <span class="keyword">return</span> Snake;
  1313. })(Animal);
  1314. Horse = (<span class="function"><span class="keyword">function</span><span class="params">(superClass)</span> {</span>
  1315. extend(Horse, superClass);
  1316. <span class="function"><span class="keyword">function</span> <span class="title">Horse</span><span class="params">()</span> {</span>
  1317. <span class="keyword">return</span> Horse.__super__.constructor.apply(<span class="keyword">this</span>, <span class="built_in">arguments</span>);
  1318. }
  1319. Horse.prototype.move = <span class="function"><span class="keyword">function</span><span class="params">()</span> {</span>
  1320. alert(<span class="string">"Galloping..."</span>);
  1321. <span class="keyword">return</span> Horse.__super__.move.call(<span class="keyword">this</span>, <span class="number">45</span>);
  1322. };
  1323. <span class="keyword">return</span> Horse;
  1324. })(Animal);
  1325. sam = <span class="keyword">new</span> Snake(<span class="string">"Sammy the Python"</span>);
  1326. tom = <span class="keyword">new</span> Horse(<span class="string">"Tommy the Palomino"</span>);
  1327. sam.move();
  1328. tom.move();
  1329. </code></pre><script>window.example24 = "class Animal\n constructor: (@name) ->\n\n move: (meters) ->\n alert @name + \" moved #{meters}m.\"\n\nclass Snake extends Animal\n move: ->\n alert \"Slithering...\"\n super 5\n\nclass Horse extends Animal\n move: ->\n alert \"Galloping...\"\n super 45\n\nsam = new Snake \"Sammy the Python\"\ntom = new Horse \"Tommy the Palomino\"\n\nsam.move()\ntom.move()\n"</script><div class='minibutton load' onclick='javascript: loadConsole(example24);'>load</div><div class='minibutton ok' onclick='javascript: var Animal, Horse, Snake, sam, tom,
  1330. extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  1331. hasProp = {}.hasOwnProperty;
  1332. Animal = (function() {
  1333. function Animal(name) {
  1334. this.name = name;
  1335. }
  1336. Animal.prototype.move = function(meters) {
  1337. return alert(this.name + (" moved " + meters + "m."));
  1338. };
  1339. return Animal;
  1340. })();
  1341. Snake = (function(superClass) {
  1342. extend(Snake, superClass);
  1343. function Snake() {
  1344. return Snake.__super__.constructor.apply(this, arguments);
  1345. }
  1346. Snake.prototype.move = function() {
  1347. alert("Slithering...");
  1348. return Snake.__super__.move.call(this, 5);
  1349. };
  1350. return Snake;
  1351. })(Animal);
  1352. Horse = (function(superClass) {
  1353. extend(Horse, superClass);
  1354. function Horse() {
  1355. return Horse.__super__.constructor.apply(this, arguments);
  1356. }
  1357. Horse.prototype.move = function() {
  1358. alert("Galloping...");
  1359. return Horse.__super__.move.call(this, 45);
  1360. };
  1361. return Horse;
  1362. })(Animal);
  1363. sam = new Snake("Sammy the Python");
  1364. tom = new Horse("Tommy the Palomino");
  1365. sam.move();
  1366. tom.move();
  1367. ;'>run</div><br class='clear' /></div>
  1368. <p>
  1369. If structuring your prototypes classically isn't your cup of tea, CoffeeScript
  1370. provides a couple of lower-level conveniences. The <code>extends</code> operator
  1371. helps with proper prototype setup, and can be used to create an inheritance
  1372. chain between any pair of constructor functions; <code>::</code> gives you
  1373. quick access to an object's prototype; and <code>super()</code>
  1374. is converted into a call against the immediate ancestor's method of the same name.
  1375. </p>
  1376. <div class='code'><pre><code><span class="attribute">String</span>::<span class="function"><span class="title">dasherize</span> = -&gt;</span>
  1377. <span class="keyword">this</span>.replace <span class="regexp">/_/g</span>, <span class="string">"-"</span>
  1378. </code></pre><pre><code><span class="built_in">String</span>.prototype.dasherize = <span class="function"><span class="keyword">function</span><span class="params">()</span> {</span>
  1379. <span class="keyword">return</span> <span class="keyword">this</span>.replace(<span class="regexp">/_/g</span>, <span class="string">"-"</span>);
  1380. };
  1381. </code></pre><script>window.example25 = "String::dasherize = ->\n this.replace /_/g, \"-\"\n"</script><div class='minibutton load' onclick='javascript: loadConsole(example25);'>load</div><div class='minibutton ok' onclick='javascript: String.prototype.dasherize = function() {
  1382. return this.replace(/_/g, "-");
  1383. };
  1384. ;alert("one_two".dasherize());'>run: "one_two".dasherize()</div><br class='clear' /></div>
  1385. <p>
  1386. Finally, class definitions are blocks of executable code, which make for interesting
  1387. metaprogramming possibilities. Because in the context of a class definition,
  1388. <code>this</code> is the class object itself (the constructor function), you
  1389. can assign static properties by using <br /><code>@property: value</code>, and call
  1390. functions defined in parent classes: <code>@attr 'title', type: 'text'</code>
  1391. </p>
  1392. <p>
  1393. <span id="destructuring" class="bookmark"></span>
  1394. <b class="header">Destructuring Assignment</b>
  1395. Just like JavaScript (since ES2015), CoffeeScript has destructuring assignment
  1396. syntax. When you assign an array or object literal to a value, CoffeeScript
  1397. breaks up and matches both sides against each other, assigning the values
  1398. on the right to the variables on the left. In the simplest case, it can be
  1399. used for parallel assignment:
  1400. </p>
  1401. <div class='code'><pre><code>theBait = <span class="number">1000</span>
  1402. theSwitch = <span class="number">0</span>
  1403. [theBait, theSwitch] = [theSwitch, theBait]
  1404. </code></pre><pre><code><span class="keyword">var</span> ref, theBait, theSwitch;
  1405. theBait = <span class="number">1000</span>;
  1406. theSwitch = <span class="number">0</span>;
  1407. ref = [theSwitch, theBait], theBait = ref[<span class="number">0</span>], theSwitch = ref[<span class="number">1</span>];
  1408. </code></pre><script>window.example26 = "theBait = 1000\ntheSwitch = 0\n\n[theBait, theSwitch] = [theSwitch, theBait]\n"</script><div class='minibutton load' onclick='javascript: loadConsole(example26);'>load</div><div class='minibutton ok' onclick='javascript: var ref, theBait, theSwitch;
  1409. theBait = 1000;
  1410. theSwitch = 0;
  1411. ref = [theSwitch, theBait], theBait = ref[0], theSwitch = ref[1];
  1412. ;alert(theBait);'>run: theBait</div><br class='clear' /></div>
  1413. <p>
  1414. But it's also helpful for dealing with functions that return multiple
  1415. values.
  1416. </p>
  1417. <div class='code'><pre><code><span class="function"><span class="title">weatherReport</span> = <span class="params">(location)</span> -&gt;</span>
  1418. <span class="comment"># Make an Ajax request to fetch the weather...</span>
  1419. [location, <span class="number">72</span>, <span class="string">"Mostly Sunny"</span>]
  1420. [city, temp, forecast] = weatherReport <span class="string">"Berkeley, CA"</span>
  1421. </code></pre><pre><code><span class="keyword">var</span> city, forecast, ref, temp, weatherReport;
  1422. weatherReport = <span class="function"><span class="keyword">function</span><span class="params">(location)</span> {</span>
  1423. <span class="keyword">return</span> [location, <span class="number">72</span>, <span class="string">"Mostly Sunny"</span>];
  1424. };
  1425. ref = weatherReport(<span class="string">"Berkeley, CA"</span>), city = ref[<span class="number">0</span>], temp = ref[<span class="number">1</span>], forecast = ref[<span class="number">2</span>];
  1426. </code></pre><script>window.example27 = "weatherReport = (location) ->\n # Make an Ajax request to fetch the weather...\n [location, 72, \"Mostly Sunny\"]\n\n[city, temp, forecast] = weatherReport \"Berkeley, CA\"\n"</script><div class='minibutton load' onclick='javascript: loadConsole(example27);'>load</div><div class='minibutton ok' onclick='javascript: var city, forecast, ref, temp, weatherReport;
  1427. weatherReport = function(location) {
  1428. return [location, 72, "Mostly Sunny"];
  1429. };
  1430. ref = weatherReport("Berkeley, CA"), city = ref[0], temp = ref[1], forecast = ref[2];
  1431. ;alert(forecast);'>run: forecast</div><br class='clear' /></div>
  1432. <p>
  1433. Destructuring assignment can be used with any depth of array and object nesting,
  1434. to help pull out deeply nested properties.
  1435. </p>
  1436. <div class='code'><pre><code>futurists =
  1437. <span class="attribute">sculptor</span>: <span class="string">"Umberto Boccioni"</span>
  1438. <span class="attribute">painter</span>: <span class="string">"Vladimir Burliuk"</span>
  1439. <span class="attribute">poet</span>:
  1440. <span class="attribute">name</span>: <span class="string">"F.T. Marinetti"</span>
  1441. <span class="attribute">address</span>: [
  1442. <span class="string">"Via Roma 42R"</span>
  1443. <span class="string">"Bellagio, Italy 22021"</span>
  1444. ]
  1445. {<span class="attribute">poet</span>: {name, <span class="attribute">address</span>: [street, city]}} = futurists
  1446. </code></pre><pre><code><span class="keyword">var</span> city, futurists, name, ref, ref1, street;
  1447. futurists = {
  1448. sculptor: <span class="string">"Umberto Boccioni"</span>,
  1449. painter: <span class="string">"Vladimir Burliuk"</span>,
  1450. poet: {
  1451. name: <span class="string">"F.T. Marinetti"</span>,
  1452. address: [<span class="string">"Via Roma 42R"</span>, <span class="string">"Bellagio, Italy 22021"</span>]
  1453. }
  1454. };
  1455. ref = futurists.poet, name = ref.name, (ref1 = ref.address, street = ref1[<span class="number">0</span>], city = ref1[<span class="number">1</span>]);
  1456. </code></pre><script>window.example28 = "futurists =\n sculptor: \"Umberto Boccioni\"\n painter: \"Vladimir Burliuk\"\n poet:\n name: \"F.T. Marinetti\"\n address: [\n \"Via Roma 42R\"\n \"Bellagio, Italy 22021\"\n ]\n\n{poet: {name, address: [street, city]}} = futurists\n"</script><div class='minibutton load' onclick='javascript: loadConsole(example28);'>load</div><div class='minibutton ok' onclick='javascript: var city, futurists, name, ref, ref1, street;
  1457. futurists = {
  1458. sculptor: "Umberto Boccioni",
  1459. painter: "Vladimir Burliuk",
  1460. poet: {
  1461. name: "F.T. Marinetti",
  1462. address: ["Via Roma 42R", "Bellagio, Italy 22021"]
  1463. }
  1464. };
  1465. ref = futurists.poet, name = ref.name, (ref1 = ref.address, street = ref1[0], city = ref1[1]);
  1466. ;alert(name + "-" + street);'>run: name + "-" + street</div><br class='clear' /></div>
  1467. <p>
  1468. Destructuring assignment can even be combined with splats.
  1469. </p>
  1470. <div class='code'><pre><code>tag = <span class="string">"&lt;impossible&gt;"</span>
  1471. [open, contents..., close] = tag.split(<span class="string">""</span>)
  1472. </code></pre><pre><code><span class="keyword">var</span> close, contents, i, open, ref, tag,
  1473. slice = [].slice;
  1474. tag = <span class="string">"&lt;impossible&gt;"</span>;
  1475. ref = tag.split(<span class="string">""</span>), open = ref[<span class="number">0</span>], contents = <span class="number">3</span> &lt;= ref.length ? slice.call(ref, <span class="number">1</span>, i = ref.length - <span class="number">1</span>) : (i = <span class="number">1</span>, []), close = ref[i++];
  1476. </code></pre><script>window.example29 = "tag = \"<impossible>\"\n\n[open, contents..., close] = tag.split(\"\")\n"</script><div class='minibutton load' onclick='javascript: loadConsole(example29);'>load</div><div class='minibutton ok' onclick='javascript: var close, contents, i, open, ref, tag,
  1477. slice = [].slice;
  1478. tag = "<impossible>";
  1479. ref = tag.split(""), open = ref[0], contents = 3 <= ref.length ? slice.call(ref, 1, i = ref.length - 1) : (i = 1, []), close = ref[i++];
  1480. ;alert(contents.join(""));'>run: contents.join("")</div><br class='clear' /></div>
  1481. <p>
  1482. Expansion can be used to retrieve elements from the end of an array without having to assign the rest of its values. It works in function parameter lists as well.
  1483. </p>
  1484. <div class='code'><pre><code>text = <span class="string">"Every literary critic believes he will
  1485. outwit history and have the last word"</span>
  1486. [first, ..., last] = text.split <span class="string">" "</span>
  1487. </code></pre><pre><code><span class="keyword">var</span> first, last, ref, text;
  1488. text = <span class="string">"Every literary critic believes he will outwit history and have the last word"</span>;
  1489. ref = text.split(<span class="string">" "</span>), first = ref[<span class="number">0</span>], last = ref[ref.length - <span class="number">1</span>];
  1490. </code></pre><script>window.example30 = "text = \"Every literary critic believes he will\n outwit history and have the last word\"\n\n[first, ..., last] = text.split \" \"\n"</script><div class='minibutton load' onclick='javascript: loadConsole(example30);'>load</div><div class='minibutton ok' onclick='javascript: var first, last, ref, text;
  1491. text = "Every literary critic believes he will outwit history and have the last word";
  1492. ref = text.split(" "), first = ref[0], last = ref[ref.length - 1];
  1493. ;alert(first + " " + last);'>run: first + " " + last</div><br class='clear' /></div>
  1494. <p>
  1495. Destructuring assignment is also useful when combined with class constructors
  1496. to assign properties to your instance from an options object passed to the constructor.
  1497. </p>
  1498. <div class='code'><pre><code><span class="class"><span class="keyword">class</span> <span class="title">Person</span></span>
  1499. <span class="attribute">constructor</span>: <span class="function"><span class="params">(options)</span> -&gt;</span>
  1500. {<span class="property">@name</span>, <span class="property">@age</span>, <span class="property">@height</span> = <span class="string">'average'</span>} = options
  1501. tim = <span class="keyword">new</span> Person <span class="attribute">name</span>: <span class="string">'Tim'</span>, <span class="attribute">age</span>: <span class="number">4</span>
  1502. </code></pre><pre><code><span class="keyword">var</span> Person, tim;
  1503. Person = (<span class="function"><span class="keyword">function</span><span class="params">()</span> {</span>
  1504. <span class="function"><span class="keyword">function</span> <span class="title">Person</span><span class="params">(options)</span> {</span>
  1505. <span class="keyword">var</span> ref;
  1506. <span class="keyword">this</span>.name = options.name, <span class="keyword">this</span>.age = options.age, <span class="keyword">this</span>.height = (ref = options.height) != <span class="literal">null</span> ? ref : <span class="string">'average'</span>;
  1507. }
  1508. <span class="keyword">return</span> Person;
  1509. })();
  1510. tim = <span class="keyword">new</span> Person({
  1511. name: <span class="string">'Tim'</span>,
  1512. age: <span class="number">4</span>
  1513. });
  1514. </code></pre><script>window.example31 = "class Person\n constructor: (options) ->\n {@name, @age, @height = 'average'} = options\n\ntim = new Person name: 'Tim', age: 4\n"</script><div class='minibutton load' onclick='javascript: loadConsole(example31);'>load</div><div class='minibutton ok' onclick='javascript: var Person, tim;
  1515. Person = (function() {
  1516. function Person(options) {
  1517. var ref;
  1518. this.name = options.name, this.age = options.age, this.height = (ref = options.height) != null ? ref : 'average';
  1519. }
  1520. return Person;
  1521. })();
  1522. tim = new Person({
  1523. name: 'Tim',
  1524. age: 4
  1525. });
  1526. ;alert(tim.age + " " + tim.height);'>run: tim.age + " " + tim.height</div><br class='clear' /></div>
  1527. <p>
  1528. The above example also demonstrates that if properties are missing in the
  1529. destructured object or array, you can, just like in JavaScript, provide
  1530. defaults. The difference with JavaScript is that CoffeeScript, as always,
  1531. treats both null and undefined the same.
  1532. </p>
  1533. <p>
  1534. <span id="fat-arrow" class="bookmark"></span>
  1535. <b class="header">Bound Functions, Generator Functions</b>
  1536. In JavaScript, the <code>this</code> keyword is dynamically scoped to mean the
  1537. object that the current function is attached to. If you pass a function as
  1538. a callback or attach it to a different object, the original value of <code>this</code>
  1539. will be lost. If you're not familiar with this behavior,
  1540. <a href="http://www.digital-web.com/articles/scope_in_javascript/">this Digital Web article</a>
  1541. gives a good overview of the quirks.
  1542. </p>
  1543. <p>
  1544. The fat arrow <code>=&gt;</code> can be used to both define a function, and to bind
  1545. it to the current value of <code>this</code>, right on the spot. This is helpful
  1546. when using callback-based libraries like Prototype or jQuery, for creating
  1547. iterator functions to pass to <code>each</code>, or event-handler functions
  1548. to use with <code>on</code>. Functions created with the fat arrow are able to access
  1549. properties of the <code>this</code> where they're defined.
  1550. </p>
  1551. <div class='code'><pre><code><span class="function"><span class="title">Account</span> = <span class="params">(customer, cart)</span> -&gt;</span>
  1552. <span class="property">@customer</span> = customer
  1553. <span class="property">@cart</span> = cart
  1554. $<span class="function"><span class="params">(<span class="string">'.shopping_cart'</span>)</span>.<span class="title">on</span> '<span class="title">click</span>', <span class="params">(event)</span> =&gt;</span>
  1555. <span class="property">@customer</span>.purchase <span class="property">@cart</span></code></pre><pre><code><span class="keyword">var</span> Account;
  1556. Account = <span class="function"><span class="keyword">function</span><span class="params">(customer, cart)</span> {</span>
  1557. <span class="keyword">this</span>.customer = customer;
  1558. <span class="keyword">this</span>.cart = cart;
  1559. <span class="keyword">return</span> $(<span class="string">'.shopping_cart'</span>).on(<span class="string">'click'</span>, (<span class="function"><span class="keyword">function</span><span class="params">(_this)</span> {</span>
  1560. <span class="keyword">return</span> <span class="function"><span class="keyword">function</span><span class="params">(event)</span> {</span>
  1561. <span class="keyword">return</span> _this.customer.purchase(_this.cart);
  1562. };
  1563. })(<span class="keyword">this</span>));
  1564. };
  1565. </code></pre><script>window.example32 = "Account = (customer, cart) ->\n @customer = customer\n @cart = cart\n\n $('.shopping_cart').on 'click', (event) =>\n @customer.purchase @cart"</script><div class='minibutton load' onclick='javascript: loadConsole(example32);'>load</div><br class='clear' /></div>
  1566. <p>
  1567. If we had used <code>-&gt;</code> in the callback above, <code>@customer</code> would
  1568. have referred to the undefined "customer" property of the DOM element,
  1569. and trying to call <code>purchase()</code> on it would have raised an exception.
  1570. </p>
  1571. <p>
  1572. When used in a class definition, methods declared with the fat arrow will
  1573. be automatically bound to each instance of the class when the instance is
  1574. constructed.
  1575. </p>
  1576. <p>
  1577. CoffeeScript functions also support
  1578. <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function*">ES6 generator functions</a>
  1579. through the <code>yield</code> keyword. There's no <code>function*(){}</code>
  1580. nonsense &mdash; a generator in CoffeeScript is simply a function that yields.
  1581. </p>
  1582. <div class='code'><pre><code><span class="function"><span class="title">perfectSquares</span> = -&gt;</span>
  1583. num = <span class="number">0</span>
  1584. <span class="keyword">loop</span>
  1585. num += <span class="number">1</span>
  1586. yield num * num
  1587. <span class="keyword">return</span>
  1588. <span class="built_in">window</span>.ps <span class="keyword">or</span>= perfectSquares()</code></pre><pre><code><span class="keyword">var</span> perfectSquares;
  1589. perfectSquares = <span class="function"><span class="keyword">function</span>*<span class="params">()</span> {</span>
  1590. <span class="keyword">var</span> num;
  1591. num = <span class="number">0</span>;
  1592. <span class="keyword">while</span> (<span class="literal">true</span>) {
  1593. num += <span class="number">1</span>;
  1594. (<span class="keyword">yield</span> num * num);
  1595. }
  1596. };
  1597. window.ps || (window.ps = perfectSquares());
  1598. </code></pre><script>window.example33 = "perfectSquares = ->\n num = 0\n loop\n num += 1\n yield num * num\n return\n\nwindow.ps or= perfectSquares()"</script><div class='minibutton load' onclick='javascript: loadConsole(example33);'>load</div><div class='minibutton ok' onclick='javascript: var perfectSquares;
  1599. perfectSquares = function*() {
  1600. var num;
  1601. num = 0;
  1602. while (true) {
  1603. num += 1;
  1604. (yield num * num);
  1605. }
  1606. };
  1607. window.ps || (window.ps = perfectSquares());
  1608. ;alert(ps.next().value);'>run: ps.next().value</div><br class='clear' /></div>
  1609. <p>
  1610. <code>yield*</code> is called <code>yield from</code>, and <code>yield return</code>
  1611. may be used if you need to force a generator that doesn't yield.
  1612. </p>
  1613. <p>
  1614. <span id="embedded" class="bookmark"></span>
  1615. <b class="header">Embedded JavaScript</b>
  1616. Hopefully, you'll never need to use it, but if you ever need to intersperse
  1617. snippets of JavaScript within your CoffeeScript, you can
  1618. use backticks to pass it straight through.
  1619. </p>
  1620. <div class='code'><pre><code>hi = `<span class="javascript"><span class="function"><span class="keyword">function</span><span class="params">()</span> {</span>
  1621. <span class="keyword">return</span> [document.title, <span class="string">"Hello JavaScript"</span>].join(<span class="string">": "</span>);
  1622. }</span>`
  1623. </code></pre><pre><code><span class="keyword">var</span> hi;
  1624. hi = <span class="function"><span class="keyword">function</span><span class="params">()</span> {</span>
  1625. <span class="keyword">return</span> [document.title, <span class="string">"Hello JavaScript"</span>].join(<span class="string">": "</span>);
  1626. };
  1627. </code></pre><script>window.example34 = "hi = `function() {\n return [document.title, \"Hello JavaScript\"].join(\": \");\n}`\n"</script><div class='minibutton load' onclick='javascript: loadConsole(example34);'>load</div><div class='minibutton ok' onclick='javascript: var hi;
  1628. hi = function() {
  1629. return [document.title, "Hello JavaScript"].join(": ");
  1630. };
  1631. ;alert(hi());'>run: hi()</div><br class='clear' /></div>
  1632. <p>
  1633. <span id="switch" class="bookmark"></span>
  1634. <b class="header">Switch/When/Else</b>
  1635. <b>Switch</b> statements in JavaScript are a bit awkward. You need to
  1636. remember to <b>break</b> at the end of every <b>case</b> statement to
  1637. avoid accidentally falling through to the default case.
  1638. CoffeeScript prevents accidental fall-through, and can convert the <code>switch</code>
  1639. into a returnable, assignable expression. The format is: <code>switch</code> condition,
  1640. <code>when</code> clauses, <code>else</code> the default case.
  1641. </p>
  1642. <p>
  1643. As in Ruby, <b>switch</b> statements in CoffeeScript can take multiple
  1644. values for each <b>when</b> clause. If any of the values match, the clause
  1645. runs.
  1646. </p>
  1647. <div class='code'><pre><code><span class="keyword">switch</span> day
  1648. <span class="keyword">when</span> <span class="string">"Mon"</span> <span class="keyword">then</span> go work
  1649. <span class="keyword">when</span> <span class="string">"Tue"</span> <span class="keyword">then</span> go relax
  1650. <span class="keyword">when</span> <span class="string">"Thu"</span> <span class="keyword">then</span> go iceFishing
  1651. <span class="keyword">when</span> <span class="string">"Fri"</span>, <span class="string">"Sat"</span>
  1652. <span class="keyword">if</span> day <span class="keyword">is</span> bingoDay
  1653. go bingo
  1654. go dancing
  1655. <span class="keyword">when</span> <span class="string">"Sun"</span> <span class="keyword">then</span> go church
  1656. <span class="keyword">else</span> go work</code></pre><pre><code><span class="keyword">switch</span> (day) {
  1657. <span class="keyword">case</span> <span class="string">"Mon"</span>:
  1658. go(work);
  1659. <span class="keyword">break</span>;
  1660. <span class="keyword">case</span> <span class="string">"Tue"</span>:
  1661. go(relax);
  1662. <span class="keyword">break</span>;
  1663. <span class="keyword">case</span> <span class="string">"Thu"</span>:
  1664. go(iceFishing);
  1665. <span class="keyword">break</span>;
  1666. <span class="keyword">case</span> <span class="string">"Fri"</span>:
  1667. <span class="keyword">case</span> <span class="string">"Sat"</span>:
  1668. <span class="keyword">if</span> (day === bingoDay) {
  1669. go(bingo);
  1670. go(dancing);
  1671. }
  1672. <span class="keyword">break</span>;
  1673. <span class="keyword">case</span> <span class="string">"Sun"</span>:
  1674. go(church);
  1675. <span class="keyword">break</span>;
  1676. <span class="keyword">default</span>:
  1677. go(work);
  1678. }
  1679. </code></pre><script>window.example35 = "switch day\n when \"Mon\" then go work\n when \"Tue\" then go relax\n when \"Thu\" then go iceFishing\n when \"Fri\", \"Sat\"\n if day is bingoDay\n go bingo\n go dancing\n when \"Sun\" then go church\n else go work"</script><div class='minibutton load' onclick='javascript: loadConsole(example35);'>load</div><br class='clear' /></div>
  1680. <p>
  1681. Switch statements can also be used without a control expression, turning them in to a cleaner alternative to if/else chains.
  1682. </p>
  1683. <div class='code'><pre><code>score = <span class="number">76</span>
  1684. grade = <span class="keyword">switch</span>
  1685. <span class="keyword">when</span> score &lt; <span class="number">60</span> <span class="keyword">then</span> <span class="string">'F'</span>
  1686. <span class="keyword">when</span> score &lt; <span class="number">70</span> <span class="keyword">then</span> <span class="string">'D'</span>
  1687. <span class="keyword">when</span> score &lt; <span class="number">80</span> <span class="keyword">then</span> <span class="string">'C'</span>
  1688. <span class="keyword">when</span> score &lt; <span class="number">90</span> <span class="keyword">then</span> <span class="string">'B'</span>
  1689. <span class="keyword">else</span> <span class="string">'A'</span>
  1690. <span class="comment"># grade == 'C'</span>
  1691. </code></pre><pre><code><span class="keyword">var</span> grade, score;
  1692. score = <span class="number">76</span>;
  1693. grade = (<span class="function"><span class="keyword">function</span><span class="params">()</span> {</span>
  1694. <span class="keyword">switch</span> (<span class="literal">false</span>) {
  1695. <span class="keyword">case</span> !(score &lt; <span class="number">60</span>):
  1696. <span class="keyword">return</span> <span class="string">'F'</span>;
  1697. <span class="keyword">case</span> !(score &lt; <span class="number">70</span>):
  1698. <span class="keyword">return</span> <span class="string">'D'</span>;
  1699. <span class="keyword">case</span> !(score &lt; <span class="number">80</span>):
  1700. <span class="keyword">return</span> <span class="string">'C'</span>;
  1701. <span class="keyword">case</span> !(score &lt; <span class="number">90</span>):
  1702. <span class="keyword">return</span> <span class="string">'B'</span>;
  1703. <span class="keyword">default</span>:
  1704. <span class="keyword">return</span> <span class="string">'A'</span>;
  1705. }
  1706. })();
  1707. </code></pre><script>window.example36 = "score = 76\ngrade = switch\n when score < 60 then 'F'\n when score < 70 then 'D'\n when score < 80 then 'C'\n when score < 90 then 'B'\n else 'A'\n# grade == 'C'\n"</script><div class='minibutton load' onclick='javascript: loadConsole(example36);'>load</div><br class='clear' /></div>
  1708. <p>
  1709. <span id="try" class="bookmark"></span>
  1710. <b class="header">Try/Catch/Finally</b>
  1711. Try-expressions have the same semantics as try-statements in JavaScript,
  1712. though in CoffeeScript, you may omit <em>both</em> the catch and finally
  1713. parts. The catch part may also omit the error parameter if it is not needed.
  1714. </p>
  1715. <div class='code'><pre><code><span class="keyword">try</span>
  1716. allHellBreaksLoose()
  1717. catsAndDogsLivingTogether()
  1718. <span class="keyword">catch</span> error
  1719. <span class="built_in">print</span> error
  1720. <span class="keyword">finally</span>
  1721. cleanUp()
  1722. </code></pre><pre><code><span class="keyword">var</span> error, error1;
  1723. <span class="keyword">try</span> {
  1724. allHellBreaksLoose();
  1725. catsAndDogsLivingTogether();
  1726. } <span class="keyword">catch</span> (error1) {
  1727. error = error1;
  1728. print(error);
  1729. } <span class="keyword">finally</span> {
  1730. cleanUp();
  1731. }
  1732. </code></pre><script>window.example37 = "try\n allHellBreaksLoose()\n catsAndDogsLivingTogether()\ncatch error\n print error\nfinally\n cleanUp()\n"</script><div class='minibutton load' onclick='javascript: loadConsole(example37);'>load</div><br class='clear' /></div>
  1733. <p>
  1734. <span id="comparisons" class="bookmark"></span>
  1735. <b class="header">Chained Comparisons</b>
  1736. CoffeeScript borrows
  1737. <a href="http://docs.python.org/reference/expressions.html#notin">chained comparisons</a>
  1738. from Python &mdash; making it easy to test if a value falls within a
  1739. certain range.
  1740. </p>
  1741. <div class='code'><pre><code>cholesterol = <span class="number">127</span>
  1742. healthy = <span class="number">200</span> &gt; cholesterol &gt; <span class="number">60</span>
  1743. </code></pre><pre><code><span class="keyword">var</span> cholesterol, healthy;
  1744. cholesterol = <span class="number">127</span>;
  1745. healthy = (<span class="number">200</span> &gt; cholesterol &amp;&amp; cholesterol &gt; <span class="number">60</span>);
  1746. </code></pre><script>window.example38 = "cholesterol = 127\n\nhealthy = 200 > cholesterol > 60\n"</script><div class='minibutton load' onclick='javascript: loadConsole(example38);'>load</div><div class='minibutton ok' onclick='javascript: var cholesterol, healthy;
  1747. cholesterol = 127;
  1748. healthy = (200 > cholesterol && cholesterol > 60);
  1749. ;alert(healthy);'>run: healthy</div><br class='clear' /></div>
  1750. <p>
  1751. <span id="strings" class="bookmark"></span>
  1752. <b class="header">String Interpolation, Block Strings, and Block Comments</b>
  1753. Ruby-style string interpolation is included in CoffeeScript. Double-quoted
  1754. strings allow for interpolated values, using <code>#{ ... }</code>,
  1755. and single-quoted strings are literal. You may even use interpolation in
  1756. object keys.
  1757. </p>
  1758. <div class='code'><pre><code>author = <span class="string">"Wittgenstein"</span>
  1759. quote = <span class="string">"A picture is a fact. -- <span class="subst">#{ author }</span>"</span>
  1760. sentence = <span class="string">"<span class="subst">#{ <span class="number">22</span> / <span class="number">7</span> }</span> is a decent approximation of π"</span>
  1761. </code></pre><pre><code><span class="keyword">var</span> author, quote, sentence;
  1762. author = <span class="string">"Wittgenstein"</span>;
  1763. quote = <span class="string">"A picture is a fact. -- "</span> + author;
  1764. sentence = (<span class="number">22</span> / <span class="number">7</span>) + <span class="string">" is a decent approximation of π"</span>;
  1765. </code></pre><script>window.example39 = "author = \"Wittgenstein\"\nquote = \"A picture is a fact. -- #{ author }\"\n\nsentence = \"#{ 22 / 7 } is a decent approximation of π\"\n"</script><div class='minibutton load' onclick='javascript: loadConsole(example39);'>load</div><div class='minibutton ok' onclick='javascript: var author, quote, sentence;
  1766. author = "Wittgenstein";
  1767. quote = "A picture is a fact. -- " + author;
  1768. sentence = (22 / 7) + " is a decent approximation of π";
  1769. ;alert(sentence);'>run: sentence</div><br class='clear' /></div>
  1770. <p>
  1771. Multiline strings are allowed in CoffeeScript. Lines are joined by a single space unless they end with a backslash. Indentation is ignored.
  1772. </p>
  1773. <div class='code'><pre><code>mobyDick = <span class="string">"Call me Ishmael. Some years ago --
  1774. never mind how long precisely -- having little
  1775. or no money in my purse, and nothing particular
  1776. to interest me on shore, I thought I would sail
  1777. about a little and see the watery part of the
  1778. world..."</span>
  1779. </code></pre><pre><code><span class="keyword">var</span> mobyDick;
  1780. mobyDick = <span class="string">"Call me Ishmael. Some years ago -- never mind how long precisely -- having little or no money in my purse, and nothing particular to interest me on shore, I thought I would sail about a little and see the watery part of the world..."</span>;
  1781. </code></pre><script>window.example40 = "mobyDick = \"Call me Ishmael. Some years ago --\n never mind how long precisely -- having little\n or no money in my purse, and nothing particular\n to interest me on shore, I thought I would sail\n about a little and see the watery part of the\n world...\"\n"</script><div class='minibutton load' onclick='javascript: loadConsole(example40);'>load</div><div class='minibutton ok' onclick='javascript: var mobyDick;
  1782. mobyDick = "Call me Ishmael. Some years ago -- never mind how long precisely -- having little or no money in my purse, and nothing particular to interest me on shore, I thought I would sail about a little and see the watery part of the world...";
  1783. ;alert(mobyDick);'>run: mobyDick</div><br class='clear' /></div>
  1784. <p>
  1785. Block strings can be used to hold formatted or indentation-sensitive text
  1786. (or, if you just don't feel like escaping quotes and apostrophes). The
  1787. indentation level that begins the block is maintained throughout, so
  1788. you can keep it all aligned with the body of your code.
  1789. </p>
  1790. <div class='code'><pre><code>html = <span class="string">"""
  1791. &lt;strong&gt;
  1792. cup of coffeescript
  1793. &lt;/strong&gt;
  1794. """</span>
  1795. </code></pre><pre><code><span class="keyword">var</span> html;
  1796. html = <span class="string">"&lt;strong&gt;\n cup of coffeescript\n&lt;/strong&gt;"</span>;
  1797. </code></pre><script>window.example41 = "html = \"\"\"\n <strong>\n cup of coffeescript\n </strong>\n \"\"\"\n"</script><div class='minibutton load' onclick='javascript: loadConsole(example41);'>load</div><div class='minibutton ok' onclick='javascript: var html;
  1798. html = "<strong>\n cup of coffeescript\n</strong>";
  1799. ;alert(html);'>run: html</div><br class='clear' /></div>
  1800. <p>
  1801. Double-quoted block strings, like other double-quoted strings, allow interpolation.
  1802. </p>
  1803. <p>
  1804. Sometimes you'd like to pass a block comment through to the generated
  1805. JavaScript. For example, when you need to embed a licensing header at
  1806. the top of a file. Block comments, which mirror the syntax for block strings,
  1807. are preserved in the generated code.
  1808. </p>
  1809. <div class='code'><pre><code><span class="comment">###
  1810. SkinnyMochaHalfCaffScript Compiler v1.0
  1811. Released under the MIT License
  1812. ###</span>
  1813. </code></pre><pre><code>
  1814. <span class="comment">/*
  1815. SkinnyMochaHalfCaffScript Compiler v1.0
  1816. Released under the MIT License
  1817. */</span>
  1818. </code></pre><script>window.example42 = "###\nSkinnyMochaHalfCaffScript Compiler v1.0\nReleased under the MIT License\n###\n\n\n"</script><div class='minibutton load' onclick='javascript: loadConsole(example42);'>load</div><br class='clear' /></div>
  1819. <p>
  1820. <span id="regexes" class="bookmark"></span>
  1821. <b class="header">Block Regular Expressions</b>
  1822. Similar to block strings and comments, CoffeeScript supports block regexes &mdash;
  1823. extended regular expressions that ignore internal whitespace and can contain
  1824. comments and interpolation. Modeled after Perl's <code>/x</code> modifier, CoffeeScript's
  1825. block regexes are delimited by <code>///</code> and go a long way towards making complex
  1826. regular expressions readable. To quote from the CoffeeScript source:
  1827. </p>
  1828. <div class='code'><pre><code>OPERATOR = <span class="regexp">/// ^ (
  1829. ?: [-=]&gt; <span class="comment"># function</span>
  1830. | [-+*/%&lt;&gt;&amp;|^!?=]= <span class="comment"># compound assign / compare</span>
  1831. | &gt;&gt;&gt;=? <span class="comment"># zero-fill right shift</span>
  1832. | ([-+:])\1 <span class="comment"># doubles</span>
  1833. | ([&amp;|&lt;&gt;])\2=? <span class="comment"># logic / shift</span>
  1834. | \?\. <span class="comment"># soak access</span>
  1835. | \.{2,3} <span class="comment"># range or splat</span>
  1836. ) ///</span>
  1837. </code></pre><pre><code><span class="keyword">var</span> OPERATOR;
  1838. OPERATOR = <span class="regexp">/^(?:[-=]&gt;|[-+*\/%&lt;&gt;&amp;|^!?=]=|&gt;&gt;&gt;=?|([-+:])\1|([&amp;|&lt;&gt;])\2=?|\?\.|\.{2,3})/</span>;
  1839. </code></pre><script>window.example43 = "OPERATOR = /// ^ (\n ?: [-=]> # function\n | [-+*/%<>&|^!?=]= # compound assign / compare\n | >>>=? # zero-fill right shift\n | ([-+:])\\1 # doubles\n | ([&|<>])\\2=? # logic / shift\n | \\?\\. # soak access\n | \\.{2,3} # range or splat\n) ///\n"</script><div class='minibutton load' onclick='javascript: loadConsole(example43);'>load</div><br class='clear' /></div>
  1840. <h2>
  1841. <span id="cake" class="bookmark"></span>
  1842. Cake, and Cakefiles
  1843. </h2>
  1844. <p>
  1845. CoffeeScript includes a (very) simple build system similar to
  1846. <a href="http://www.gnu.org/software/make/">Make</a> and
  1847. <a href="http://rake.rubyforge.org/">Rake</a>. Naturally,
  1848. it's called Cake, and is used for the tasks that build and test the CoffeeScript
  1849. language itself. Tasks are defined in a file named <code>Cakefile</code>, and
  1850. can be invoked by running <code>cake [task]</code> from within the directory.
  1851. To print a list of all the tasks and options, just type <code>cake</code>.
  1852. </p>
  1853. <p>
  1854. Task definitions are written in CoffeeScript, so you can put arbitrary code
  1855. in your Cakefile. Define a task with a name, a long description, and the
  1856. function to invoke when the task is run. If your task takes a command-line
  1857. option, you can define the option with short and long flags, and it will
  1858. be made available in the <code>options</code> object. Here's a task that uses
  1859. the Node.js API to rebuild CoffeeScript's parser:
  1860. </p>
  1861. <div class='code'><pre><code>fs = <span class="built_in">require</span> <span class="string">'fs'</span>
  1862. option <span class="string">'-o'</span>, <span class="string">'--output [DIR]'</span>, <span class="string">'directory for compiled code'</span>
  1863. task <span class="string">'build:parser'</span>, <span class="string">'rebuild the Jison parser'</span>, <span class="function"><span class="params">(options)</span> -&gt;</span>
  1864. <span class="built_in">require</span> <span class="string">'jison'</span>
  1865. code = <span class="built_in">require</span>(<span class="string">'./lib/grammar'</span>).parser.generate()
  1866. dir = options.output <span class="keyword">or</span> <span class="string">'lib'</span>
  1867. fs.writeFile <span class="string">"<span class="subst">#{dir}</span>/parser.js"</span>, code</code></pre><pre><code><span class="keyword">var</span> fs;
  1868. fs = <span class="built_in">require</span>(<span class="string">'fs'</span>);
  1869. option(<span class="string">'-o'</span>, <span class="string">'--output [DIR]'</span>, <span class="string">'directory for compiled code'</span>);
  1870. task(<span class="string">'build:parser'</span>, <span class="string">'rebuild the Jison parser'</span>, <span class="function"><span class="keyword">function</span><span class="params">(options)</span> {</span>
  1871. <span class="keyword">var</span> code, dir;
  1872. <span class="built_in">require</span>(<span class="string">'jison'</span>);
  1873. code = <span class="built_in">require</span>(<span class="string">'./lib/grammar'</span>).parser.generate();
  1874. dir = options.output || <span class="string">'lib'</span>;
  1875. <span class="keyword">return</span> fs.writeFile(dir + <span class="string">"/parser.js"</span>, code);
  1876. });
  1877. </code></pre><script>window.example44 = "fs = require 'fs'\n\noption '-o', '--output [DIR]', 'directory for compiled code'\n\ntask 'build:parser', 'rebuild the Jison parser', (options) ->\n require 'jison'\n code = require('./lib/grammar').parser.generate()\n dir = options.output or 'lib'\n fs.writeFile \"#{dir}/parser.js\", code"</script><div class='minibutton load' onclick='javascript: loadConsole(example44);'>load</div><br class='clear' /></div>
  1878. <p>
  1879. If you need to invoke one task before another &mdash; for example, running
  1880. <code>build</code> before <code>test</code>, you can use the <code>invoke</code> function:
  1881. <code>invoke 'build'</code>. Cake tasks are a minimal way to expose your
  1882. CoffeeScript functions to the command line, so
  1883. <a href="documentation/docs/cake.html">don't expect any fanciness built-in</a>.
  1884. If you need dependencies, or async callbacks, it's best to put them in your
  1885. code itself &mdash; not the cake task.
  1886. </p>
  1887. <h2>
  1888. <span id="source-maps" class="bookmark"></span>
  1889. Source Maps
  1890. </h2>
  1891. <p>
  1892. CoffeeScript 1.6.1 and above include support for generating source maps,
  1893. a way to tell your JavaScript engine what part of your CoffeeScript
  1894. program matches up with the code being evaluated. Browsers that support it
  1895. can automatically use source maps to show your original source code
  1896. in the debugger. To generate source maps alongside your JavaScript files,
  1897. pass the <code>--map</code> or <code>-m</code> flag to the compiler.
  1898. </p>
  1899. <p>
  1900. For a full introduction to source maps, how they work, and how to hook
  1901. them up in your browser, read the
  1902. <a href="http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/">HTML5 Tutorial</a>.
  1903. </p>
  1904. <h2>
  1905. <span id="scripts" class="bookmark"></span>
  1906. "text/coffeescript" Script Tags
  1907. </h2>
  1908. <p>
  1909. While it's not recommended for serious use, CoffeeScripts may be included
  1910. directly within the browser using <code>&lt;script type="text/coffeescript"&gt;</code>
  1911. tags. The source includes a compressed and minified version of the compiler
  1912. (<a href="extras/coffee-script.js">Download current version here, 39k when gzipped</a>)
  1913. as <code>extras/coffee-script.js</code>. Include this file on a page with
  1914. inline CoffeeScript tags, and it will compile and evaluate them in order.
  1915. </p>
  1916. <p>
  1917. In fact, the little bit of glue script that runs "Try CoffeeScript" above,
  1918. as well as the jQuery for the menu, is implemented in just this way.
  1919. View source and look at the bottom of the page to see the example.
  1920. Including the script also gives you access to <code>CoffeeScript.compile()</code>
  1921. so you can pop open Firebug and try compiling some strings.
  1922. </p>
  1923. <p>
  1924. The usual caveats about CoffeeScript apply &mdash; your inline scripts will
  1925. run within a closure wrapper, so if you want to expose global variables or
  1926. functions, attach them to the <code>window</code> object.
  1927. </p>
  1928. <h2>
  1929. <span id="resources" class="bookmark"></span>
  1930. Books
  1931. </h2>
  1932. <p>
  1933. There are a number of excellent resources to help you get
  1934. started with CoffeeScript, some of which are freely available online.
  1935. </p>
  1936. <ul>
  1937. <li>
  1938. <a href="http://arcturo.github.com/library/coffeescript/">The Little Book on CoffeeScript</a>
  1939. is a brief 5-chapter introduction to CoffeeScript, written with great
  1940. clarity and precision by
  1941. <a href="http://alexmaccaw.co.uk/">Alex MacCaw</a>.
  1942. </li>
  1943. <li>
  1944. <a href="http://autotelicum.github.com/Smooth-CoffeeScript/">Smooth CoffeeScript</a>
  1945. is a reimagination of the excellent book
  1946. <a href="http://eloquentjavascript.net/">Eloquent JavaScript</a>, as if
  1947. it had been written in CoffeeScript instead. Covers language features
  1948. as well as the functional and object oriented programming styles. By
  1949. <a href="https://github.com/autotelicum">E. Hoigaard</a>.
  1950. </li>
  1951. <li>
  1952. <a href="http://pragprog.com/book/tbcoffee/coffeescript">CoffeeScript: Accelerated JavaScript Development</a>
  1953. is <a href="http://trevorburnham.com/">Trevor Burnham</a>'s thorough
  1954. introduction to the language. By the end of the book, you'll have built
  1955. a fast-paced multiplayer word game, writing both the client-side and Node.js
  1956. portions in CoffeeScript.
  1957. </li>
  1958. <li>
  1959. <a href="http://www.packtpub.com/coffeescript-programming-with-jquery-rails-nodejs/book">CoffeeScript Programming with jQuery, Rails, and Node.js</a>
  1960. is a new book by Michael Erasmus that covers CoffeeScript with an eye
  1961. towards real-world usage both in the browser (jQuery) and on the server
  1962. size (Rails, Node).
  1963. </li>
  1964. <li>
  1965. <a href="https://leanpub.com/coffeescript-ristretto/read">CoffeeScript Ristretto</a>
  1966. is a deep dive into CoffeeScript's semantics from simple functions up through
  1967. closures, higher-order functions, objects, classes, combinators, and decorators.
  1968. By <a href="http://braythwayt.com/">Reg Braithwaite</a>.
  1969. </li>
  1970. <li>
  1971. <a href="https://efendibooks.com/minibooks/testing-with-coffeescript">Testing with CoffeeScript</a>
  1972. is a succinct and freely downloadable guide to building testable
  1973. applications with CoffeeScript and Jasmine.
  1974. </li>
  1975. <li>
  1976. <a href="http://www.packtpub.com/coffeescript-application-development/book">CoffeeScript Application Development</a>
  1977. from Packt, introduces CoffeeScript while
  1978. walking through the process of building a demonstration web application.
  1979. A <a href="https://www.packtpub.com/web-development/coffeescript-application-development-cookbook">CoffeeScript Application Development Coookbook</a>
  1980. with over 90 "recipes" is also available.
  1981. </li>
  1982. <li>
  1983. <a href="http://www.manning.com/lee/">CoffeeScript in Action</a>
  1984. from Manning Publications, covers CoffeeScript syntax, composition techniques
  1985. and application development.
  1986. </li>
  1987. <li>
  1988. <a href="http://www.dpunkt.de/buecher/4021/coffeescript.html">CoffeeScript: Die Alternative zu JavaScript</a>
  1989. from dpunkt.verlag, is the first CoffeeScript book in Deutsch.
  1990. </li>
  1991. </ul>
  1992. <h2>
  1993. Screencasts
  1994. </h2>
  1995. <ul>
  1996. <li>
  1997. <a href="http://coffeescript.codeschool.com">A Sip of CoffeeScript</a> is a <a href="http://www.codeschool.com">Code School Course</a>
  1998. which combines 6 screencasts with in-browser coding to make learning fun. The first level is free to try out.
  1999. </li>
  2000. <li>
  2001. <a href="http://peepcode.com/products/coffeescript">Meet CoffeeScript</a>
  2002. is a 75-minute long screencast by <a href="http://peepcode.com/">PeepCode</a>.
  2003. Highly memorable for its animations which demonstrate transforming CoffeeScript
  2004. into the equivalent JS.
  2005. </li>
  2006. <li>
  2007. If you're looking for less of a time commitment, RailsCasts'
  2008. <a href="http://railscasts.com/episodes/267-coffeescript-basics">CoffeeScript Basics</a>
  2009. should have you covered, hitting all of the important notes about CoffeeScript
  2010. in 11 minutes.
  2011. </li>
  2012. </ul>
  2013. <h2>
  2014. Examples
  2015. </h2>
  2016. <p>
  2017. The <a href="https://github.com/trending?l=coffeescript&amp;since=monthly">best list of
  2018. open-source CoffeeScript examples</a> can be found on GitHub. But just
  2019. to throw out few more:
  2020. </p>
  2021. <ul>
  2022. <li>
  2023. <b>github</b>'s <a href="http://hubot.github.com/">Hubot</a>,
  2024. a friendly IRC robot that can perform any number of useful and useless tasks.
  2025. </li>
  2026. <li>
  2027. <b>sstephenson</b>'s <a href="http://pow.cx/">Pow</a>,
  2028. a zero-configuration Rack server, with comprehensive annotated source.
  2029. </li>
  2030. <li>
  2031. <b>technoweenie</b>'s <a href="https://github.com/technoweenie/coffee-resque">Coffee-Resque</a>,
  2032. a port of <a href="https://github.com/defunkt/resque">Resque</a> for Node.js.
  2033. </li>
  2034. <li>
  2035. <b>assaf</b>'s <a href="http://zombie.labnotes.org/">Zombie.js</a>,
  2036. a headless, full-stack, faux-browser testing library for Node.js.
  2037. </li>
  2038. <li>
  2039. <b>jashkenas</b>' <a href="documentation/docs/underscore.html">Underscore.coffee</a>, a port
  2040. of the <a href="http://documentcloud.github.com/underscore/">Underscore.js</a>
  2041. library of helper functions.
  2042. </li>
  2043. <li>
  2044. <b>stephank</b>'s <a href="https://github.com/stephank/orona">Orona</a>, a remake of
  2045. the Bolo tank game for modern browsers.
  2046. </li>
  2047. <li>
  2048. <b>github</b>'s <a href="https://atom.io/">Atom</a>,
  2049. a hackable text editor built on web technologies.
  2050. </li>
  2051. </ul>
  2052. <h2>
  2053. Resources
  2054. </h2>
  2055. <ul>
  2056. <li>
  2057. <a href="http://github.com/jashkenas/coffeescript/">Source Code</a><br />
  2058. Use <code>bin/coffee</code> to test your changes,<br />
  2059. <code>bin/cake test</code> to run the test suite,<br />
  2060. <code>bin/cake build</code> to rebuild the CoffeeScript compiler, and <br />
  2061. <code>bin/cake build:parser</code> to regenerate the Jison parser if you're
  2062. working on the grammar. <br /><br />
  2063. <code>git checkout lib &amp;&amp; bin/cake build:full</code> is a good command to run when you're working
  2064. on the core language. It'll refresh the lib directory
  2065. (in case you broke something), build your altered compiler, use that to
  2066. rebuild itself (a good sanity test) and then run all of the tests. If
  2067. they pass, there's a good chance you've made a successful change.
  2068. </li>
  2069. <li>
  2070. <a href="http://github.com/jashkenas/coffeescript/issues">CoffeeScript Issues</a><br />
  2071. Bug reports, feature proposals, and ideas for changes to the language belong here.
  2072. </li>
  2073. <li>
  2074. <a href="https://groups.google.com/forum/#!forum/coffeescript">CoffeeScript Google Group</a><br />
  2075. If you'd like to ask a question, the mailing list is a good place to get help.
  2076. </li>
  2077. <li>
  2078. <a href="http://github.com/jashkenas/coffeescript/wiki">The CoffeeScript Wiki</a><br />
  2079. If you've ever learned a neat CoffeeScript tip or trick, or ran into a gotcha &mdash; share it on the wiki.
  2080. The wiki also serves as a directory of handy
  2081. <a href="http://github.com/jashkenas/coffeescript/wiki/Text-editor-plugins">text editor extensions</a>,
  2082. <a href="http://github.com/jashkenas/coffeescript/wiki/Web-framework-plugins">web framework plugins</a>,
  2083. and general <a href="http://github.com/jashkenas/coffeescript/wiki/Build-tools">CoffeeScript build tools</a>.
  2084. </li>
  2085. <li>
  2086. <a href="http://github.com/jashkenas/coffeescript/wiki/FAQ">The FAQ</a><br />
  2087. Perhaps your CoffeeScript-related question has been asked before. Check the FAQ first.
  2088. </li>
  2089. <li>
  2090. <a href="http://js2coffee.org">JS2Coffee</a><br />
  2091. Is a very well done reverse JavaScript-to-CoffeeScript compiler. It's
  2092. not going to be perfect (infer what your JavaScript classes are, when
  2093. you need bound functions, and so on...) &mdash; but it's a great starting
  2094. point for converting simple scripts.
  2095. </li>
  2096. <li>
  2097. <a href="https://github.com/jashkenas/coffeescript/downloads">High-Rez Logo</a><br />
  2098. The CoffeeScript logo is available in Illustrator, EPS and PSD formats, for use
  2099. in presentations.
  2100. </li>
  2101. </ul>
  2102. <h2>
  2103. <span id="webchat" class="bookmark"></span>
  2104. Web Chat (IRC)
  2105. </h2>
  2106. <p>
  2107. Quick help and advice can usually be found in the CoffeeScript IRC room.
  2108. Join <code>#coffeescript</code> on <code>irc.freenode.net</code>, or click the
  2109. button below to open a webchat session on this page.
  2110. </p>
  2111. <p>
  2112. <button id="open_webchat">click to open #coffeescript</button>
  2113. </p>
  2114. <h2>
  2115. <span id="changelog" class="bookmark"></span>
  2116. Change Log
  2117. </h2>
  2118. <p>
  2119. <div class="anchor" id="1.10.0"></div>
  2120. <b class="header">
  2121. <a href="https://github.com/jashkenas/coffeescript/compare/1.9.3...1.10.0">1.10.0</a>
  2122. <span class="timestamp"> &mdash; <time datetime="2015-09-03">September 3, 2015</time></span>
  2123. </b>
  2124. <ul>
  2125. <li>
  2126. CoffeeScript now supports ES6-style destructuring defaults.
  2127. </li>
  2128. <li>
  2129. <code>(offsetHeight: height) -&gt;</code> no longer compiles. That
  2130. syntax was accidental and partly broken. Use <code>({offsetHeight: height}) -&gt;</code>
  2131. instead. Object destructuring always requires braces.
  2132. </li>
  2133. <li>
  2134. <p>Several minor bug fixes, including:</p>
  2135. <ul>
  2136. <li>
  2137. A bug where the REPL would sometimes report valid code as invalid,
  2138. based on what you had typed earlier.
  2139. </li>
  2140. <li>
  2141. A problem with multiple JS contexts in the jest test framework.
  2142. </li>
  2143. <li>
  2144. An error in io.js where strict mode is set on internal modules.
  2145. </li>
  2146. <li>
  2147. A variable name clash for the caught error in <code>catch</code>
  2148. blocks.
  2149. </li>
  2150. </ul>
  2151. </li>
  2152. </ul>
  2153. </p>
  2154. <p>
  2155. <div class="anchor" id="1.9.3"></div>
  2156. <b class="header">
  2157. <a href="https://github.com/jashkenas/coffeescript/compare/1.9.2...1.9.3">1.9.3</a>
  2158. <span class="timestamp"> &mdash; <time datetime="2015-05-27">May 27, 2015</time></span>
  2159. </b>
  2160. <ul>
  2161. <li>
  2162. Bugfix for interpolation in the first key of an object literal in an
  2163. implicit call.
  2164. </li>
  2165. <li>
  2166. Fixed broken error messages in the REPL, as well as a few minor bugs
  2167. with the REPL.
  2168. </li>
  2169. <li>
  2170. Fixed source mappings for tokens at the beginning of lines when
  2171. compiling with the <code>--bare</code> option. This has the nice side
  2172. effect of generating smaller source maps.
  2173. </li>
  2174. <li>
  2175. Slight formatting improvement of compiled block comments.
  2176. </li>
  2177. <li>
  2178. Better error messages for <code>on</code>, <code>off</code>, <code>yes</code> and
  2179. <code>no</code>.
  2180. </li>
  2181. </ul>
  2182. </p>
  2183. <p>
  2184. <div class="anchor" id="1.9.2"></div>
  2185. <b class="header">
  2186. <a href="https://github.com/jashkenas/coffeescript/compare/1.9.1...1.9.2">1.9.2</a>
  2187. <span class="timestamp"> &mdash; <time datetime="2015-04-15">April 15, 2015</time></span>
  2188. </b>
  2189. <ul>
  2190. <li>
  2191. Fixed a <b>watch</b> mode error introduced in 1.9.1 when compiling
  2192. multiple files with the same filename.
  2193. </li>
  2194. <li>
  2195. Bugfix for <code>yield</code> around expressions containing
  2196. <code>this</code>.
  2197. </li>
  2198. <li>
  2199. Added a Ruby-style <code>-r</code> option to the REPL, which allows
  2200. requiring a module before execution with <code>--eval</code> or
  2201. <code>--interactive</code>.
  2202. </li>
  2203. <li>
  2204. In <code>&lt;script type="text/coffeescript"&gt;</code> tags, to avoid
  2205. possible duplicate browser requests for .coffee files,
  2206. you can now use the <code>data-src</code> attribute instead of <code>src</code>.
  2207. </li>
  2208. <li>
  2209. Minor bug fixes for IE8, strict ES5 regular expressions and Browserify.
  2210. </li>
  2211. </ul>
  2212. </p>
  2213. <p>
  2214. <div class="anchor" id="1.9.1"></div>
  2215. <b class="header">
  2216. <a href="https://github.com/jashkenas/coffeescript/compare/1.9.0...1.9.1">1.9.1</a>
  2217. <span class="timestamp"> &mdash; <time datetime="2015-02-18">February 18, 2015</time></span>
  2218. </b>
  2219. <ul>
  2220. <li>
  2221. Interpolation now works in object literal keys (again). You can use this to
  2222. dynamically name properties.
  2223. </li>
  2224. <li>
  2225. Internal compiler variable names no longer start with underscores. This makes
  2226. the generated JavaScript a bit prettier, and also fixes an issue with
  2227. the completely broken and ungodly way that AngularJS "parses" function
  2228. arguments.
  2229. </li>
  2230. <li>
  2231. Fixed a few <code>yield</code>-related edge cases with <code>yield return</code>
  2232. and <code>yield throw</code>.
  2233. </li>
  2234. <li>
  2235. Minor bug fixes and various improvements to compiler error messages.
  2236. </li>
  2237. </ul>
  2238. </p>
  2239. <p>
  2240. <div class="anchor" id="1.9.0"></div>
  2241. <b class="header">
  2242. <a href="https://github.com/jashkenas/coffeescript/compare/1.8.0...1.9.0">1.9.0</a>
  2243. <span class="timestamp"> &mdash; <time datetime="2015-01-29">January 29, 2015</time></span>
  2244. </b>
  2245. <ul>
  2246. <li>
  2247. CoffeeScript now supports ES6 generators. A generator is simply a function
  2248. that <code>yield</code>s.
  2249. </li>
  2250. <li>
  2251. More robust parsing and improved error messages for strings and regexes
  2252. especially with respect to interpolation.
  2253. </li>
  2254. <li>
  2255. Changed strategy for the generation of internal compiler variable names.
  2256. Note that this means that <code>@example</code> function parameters are no longer
  2257. available as naked <code>example</code> variables within the function body.
  2258. </li>
  2259. <li>
  2260. Fixed REPL compatibility with latest versions of Node and Io.js.
  2261. </li>
  2262. <li>
  2263. Various minor bug fixes.
  2264. </li>
  2265. </ul>
  2266. </p>
  2267. <p>
  2268. <div class="anchor" id="1.8.0"></div>
  2269. <b class="header">
  2270. <a href="https://github.com/jashkenas/coffeescript/compare/1.7.1...1.8.0">1.8.0</a>
  2271. <span class="timestamp"> &mdash; <time datetime="2014-08-26">August 26, 2014</time></span>
  2272. </b>
  2273. <ul>
  2274. <li>
  2275. The <code>--join</code> option of the CLI is now deprecated.
  2276. </li>
  2277. <li>
  2278. Source maps now use <code>.js.map</code> as file extension, instead of just <code>.map</code>.
  2279. </li>
  2280. <li>
  2281. The CLI now exits with the exit code 1 when it fails to write a file to disk.
  2282. </li>
  2283. <li>
  2284. The compiler no longer crashes on unterminated, single-quoted strings.
  2285. </li>
  2286. <li>
  2287. Fixed location data for string interpolations, which made source maps out of sync.
  2288. </li>
  2289. <li>
  2290. The error marker in error messages is now correctly positioned if the code is indented with tabs.
  2291. </li>
  2292. <li>
  2293. Fixed a slight formatting error in CoffeeScripts source map-patched stack traces.
  2294. </li>
  2295. <li>
  2296. The <code>%%</code> operator now coerces its right operand only once.
  2297. </li>
  2298. <li>
  2299. It is now possible to require CoffeeScript files from Cakefiles without having to register the compiler first.
  2300. </li>
  2301. <li>
  2302. The CoffeeScript REPL is now exported and can be required using <code>require 'coffee-script/repl'</code>.
  2303. </li>
  2304. <li>
  2305. Fixes for the REPL in Node 0.11.
  2306. </li>
  2307. </ul>
  2308. </p>
  2309. <p>
  2310. <div class="anchor" id="1.7.1"></div>
  2311. <b class="header">
  2312. <a href="https://github.com/jashkenas/coffeescript/compare/1.7.0...1.7.1">1.7.1</a>
  2313. <span class="timestamp"> &mdash; <time datetime="2014-01-29">January 29, 2014</time></span>
  2314. </b>
  2315. <ul>
  2316. <li>
  2317. Fixed a typo that broke node module lookup when running a script directly with the <code>coffee</code> binary.
  2318. </li>
  2319. </ul>
  2320. </p>
  2321. <p>
  2322. <div class="anchor" id="1.7.0"></div>
  2323. <b class="header">
  2324. <a href="https://github.com/jashkenas/coffeescript/compare/1.6.3...1.7.0">1.7.0</a>
  2325. <span class="timestamp"> &mdash; <time datetime="2014-01-28">January 28, 2014</time></span>
  2326. </b>
  2327. <ul>
  2328. <li>
  2329. When requiring CoffeeScript files in Node you must now explicitly register the compiler. This can be done with <code>require 'coffee-script/register'</code> or <code>CoffeeScript.register()</code>. Also for configuration such as Mocha's, use <b>coffee-script/register</b>.
  2330. </li>
  2331. <li>
  2332. Improved error messages, source maps and stack traces. Source maps now use the updated <code>//#</code> syntax.
  2333. </li>
  2334. <li>
  2335. Leading <code>.</code> now closes all open calls, allowing for simpler chaining syntax.
  2336. </li>
  2337. </ul>
  2338. <div class='code'><pre><code>$ <span class="string">'body'</span>
  2339. .click <span class="function"><span class="params">(e)</span> -&gt;</span>
  2340. $ <span class="string">'.box'</span>
  2341. .fadeIn <span class="string">'fast'</span>
  2342. .addClass <span class="string">'.active'</span>
  2343. .css <span class="string">'background'</span>, <span class="string">'white'</span>
  2344. </code></pre><pre><code>$(<span class="string">'body'</span>).click(<span class="function"><span class="keyword">function</span><span class="params">(e)</span> {</span>
  2345. <span class="keyword">return</span> $(<span class="string">'.box'</span>).fadeIn(<span class="string">'fast'</span>).addClass(<span class="string">'.active'</span>);
  2346. }).css(<span class="string">'background'</span>, <span class="string">'white'</span>);
  2347. </code></pre><script>window.example45 = "$ 'body'\n.click (e) ->\n $ '.box'\n .fadeIn 'fast'\n .addClass '.active'\n.css 'background', 'white'\n"</script><div class='minibutton load' onclick='javascript: loadConsole(example45);'>load</div><br class='clear' /></div>
  2348. <ul>
  2349. <li>
  2350. Added <code>**</code>, <code>//</code> and <code>%%</code> operators and <code>...</code> expansion in parameter lists and destructuring expressions.
  2351. </li>
  2352. <li>
  2353. Multiline strings are now joined by a single space and ignore all indentation. A backslash at the end of a line can denote the amount of whitespace between lines, in both strings and heredocs. Backslashes correctly escape whitespace in block regexes.
  2354. </li>
  2355. <li>
  2356. Closing brackets can now be indented and therefore no longer cause unexpected error.
  2357. </li>
  2358. <li>
  2359. Several breaking compilation fixes. Non-callable literals (strings, numbers etc.) don't compile in a call now and multiple postfix conditionals compile properly. Postfix conditionals and loops always bind object literals. Conditional assignment compiles properly in subexpressions. <code>super</code> is disallowed outside of methods and works correctly inside <code>for</code> loops.
  2360. </li>
  2361. <li>
  2362. Formatting of compiled block comments has been improved.
  2363. </li>
  2364. <li>
  2365. No more <code>-p</code> folders on Windows.
  2366. </li>
  2367. <li>
  2368. The <code>options</code> object passed to CoffeeScript is no longer mutated.
  2369. </li>
  2370. </ul>
  2371. </p>
  2372. <p>
  2373. <div class="anchor" id="1.6.3"></div>
  2374. <b class="header">
  2375. <a href="https://github.com/jashkenas/coffeescript/compare/1.6.2...1.6.3">1.6.3</a>
  2376. <span class="timestamp"> &mdash; <time datetime="2013-06-02">June 2, 2013</time></span>
  2377. </b>
  2378. <ul>
  2379. <li>
  2380. The CoffeeScript REPL now remembers your history between sessions.
  2381. Just like a proper REPL should.
  2382. </li>
  2383. <li>
  2384. You can now use <code>require</code> in Node to load <code>.coffee.md</code>
  2385. Literate CoffeeScript files. In the browser,
  2386. <code>text/literate-coffeescript</code> script tags.
  2387. </li>
  2388. <li>
  2389. The old <code>coffee --lint</code> command has been removed. It was useful
  2390. while originally working on the compiler, but has been surpassed by
  2391. JSHint. You may now use <code>-l</code> to pass literate files in over
  2392. <b>stdio</b>.
  2393. </li>
  2394. <li>
  2395. Bugfixes for Windows path separators, <code>catch</code> without naming
  2396. the error, and executable-class-bodies-with-
  2397. prototypal-property-attachment.
  2398. </li>
  2399. </ul>
  2400. </p>
  2401. <p>
  2402. <div class="anchor" id="1.6.2"></div>
  2403. <b class="header">
  2404. <a href="https://github.com/jashkenas/coffeescript/compare/1.6.1...1.6.2">1.6.2</a>
  2405. <span class="timestamp"> &mdash; <time datetime="2013-03-18">March 18, 2013</time></span>
  2406. </b>
  2407. <ul>
  2408. <li>
  2409. Source maps have been used to provide automatic line-mapping when
  2410. running CoffeeScript directly via the <code>coffee</code> command, and
  2411. for automatic line-mapping when running CoffeeScript directly in the
  2412. browser. Also, to provide better error messages for semantic errors
  2413. thrown by the compiler &mdash;
  2414. <a href="http://cl.ly/NdOA">with colors, even</a>.
  2415. </li>
  2416. <li>
  2417. Improved support for mixed literate/vanilla-style CoffeeScript projects,
  2418. and generating source maps for both at the same time.
  2419. </li>
  2420. <li>
  2421. Fixes for <b>1.6.x</b> regressions with overriding inherited bound
  2422. functions, and for Windows file path management.
  2423. </li>
  2424. <li>
  2425. The <code>coffee</code> command can now correctly <code>fork()</code>
  2426. both <code>.coffee</code> and <code>.js</code> files. (Requires Node.js 0.9+)
  2427. </li>
  2428. </ul>
  2429. </p>
  2430. <p>
  2431. <div class="anchor" id="1.6.1"></div>
  2432. <b class="header">
  2433. <a href="https://github.com/jashkenas/coffeescript/compare/1.5.0...1.6.1">1.6.1</a>
  2434. <span class="timestamp"> &mdash; <time datetime="2013-03-05">March 5, 2013</time></span>
  2435. </b>
  2436. <ul>
  2437. <li>
  2438. First release of <a href="#source-maps">source maps</a>. Pass the
  2439. <code>--map</code> flag to the compiler, and off you go. Direct all your
  2440. thanks over to <a href="http://github.com/jwalton">Jason Walton</a>.
  2441. </li>
  2442. <li>
  2443. Fixed a 1.5.0 regression with multiple implicit calls against an
  2444. indented implicit object. Combinations of implicit function calls
  2445. and implicit objects should generally be parsed better now &mdash;
  2446. but it still isn't good <i>style</i> to nest them too heavily.
  2447. </li>
  2448. <li>
  2449. <code>.coffee.md</code> is now also supported as a Literate CoffeeScript
  2450. file extension, for existing tooling.
  2451. <code>.litcoffee</code> remains the canonical one.
  2452. </li>
  2453. <li>
  2454. Several minor fixes surrounding member properties, bound methods and
  2455. <code>super</code> in class declarations.
  2456. </li>
  2457. </ul>
  2458. </p>
  2459. <p>
  2460. <div class="anchor" id="1.5.0"></div>
  2461. <b class="header">
  2462. <a href="https://github.com/jashkenas/coffeescript/compare/1.4.0...1.5.0">1.5.0</a>
  2463. <span class="timestamp"> &mdash; <time datetime="2013-02-25">February 25, 2013</time></span>
  2464. </b>
  2465. <ul>
  2466. <li>
  2467. First release of <a href="#literate">Literate CoffeeScript</a>.
  2468. </li>
  2469. <li>
  2470. The CoffeeScript REPL is now based on the Node.js REPL, and should work
  2471. better and more familiarly.
  2472. </li>
  2473. <li>
  2474. Returning explicit values from constructors is now forbidden. If you want
  2475. to return an arbitrary value, use a function, not a constructor.
  2476. </li>
  2477. <li>
  2478. You can now loop over an array backwards, without having to manually
  2479. deal with the indexes: <code>for item in list by -1</code>
  2480. </li>
  2481. <li>
  2482. Source locations are now preserved in the CoffeeScript AST, although
  2483. source maps are not yet being emitted.
  2484. </li>
  2485. </ul>
  2486. </p>
  2487. <p>
  2488. <div class="anchor" id="1.4.0"></div>
  2489. <b class="header">
  2490. <a href="https://github.com/jashkenas/coffeescript/compare/1.3.3...1.4.0">1.4.0</a>
  2491. <span class="timestamp"> &mdash; <time datetime="2012-10-23">October 23, 2012</time></span>
  2492. </b>
  2493. <ul>
  2494. <li>
  2495. The CoffeeScript compiler now strips Microsoft's UTF-8 BOM if it
  2496. exists, allowing you to compile BOM-borked source files.
  2497. </li>
  2498. <li>
  2499. Fix Node/compiler deprecation warnings by removing <code>registerExtension</code>,
  2500. and moving from <code>path.exists</code> to <code>fs.exists</code>.
  2501. </li>
  2502. <li>
  2503. Small tweaks to splat compilation, backticks, slicing, and the
  2504. error for duplicate keys in object literals.
  2505. </li>
  2506. </ul>
  2507. </p>
  2508. <p>
  2509. <div class="anchor" id="1.3.3"></div>
  2510. <b class="header">
  2511. <a href="https://github.com/jashkenas/coffeescript/compare/1.3.1...1.3.3">1.3.3</a>
  2512. <span class="timestamp"> &mdash; <time datetime="2012-05-15">May 15, 2012</time></span>
  2513. </b>
  2514. <ul>
  2515. <li>
  2516. Due to the new semantics of JavaScript's strict mode, CoffeeScript no
  2517. longer guarantees that constructor functions have names in all runtimes.
  2518. See <a href="https://github.com/jashkenas/coffeescript/issues/2052">#2052</a>
  2519. for discussion.
  2520. </li>
  2521. <li>
  2522. Inside of a nested function inside of an instance method, it's now possible
  2523. to call <code>super</code> more reliably (walks recursively up).
  2524. </li>
  2525. <li>
  2526. Named loop variables no longer have different scoping heuristics than
  2527. other local variables. (Reverts #643)
  2528. </li>
  2529. <li>
  2530. Fix for splats nested within the LHS of destructuring assignment.
  2531. </li>
  2532. <li>
  2533. Corrections to our compile time strict mode forbidding of octal literals.
  2534. </li>
  2535. </ul>
  2536. </p>
  2537. <p>
  2538. <div class="anchor" id="1.3.1"></div>
  2539. <b class="header">
  2540. <a href="https://github.com/jashkenas/coffeescript/compare/1.2.0...1.3.1">1.3.1</a>
  2541. <span class="timestamp"> &mdash; <time datetime="2012-04-10">April 10, 2012</time></span>
  2542. </b>
  2543. <ul>
  2544. <li>
  2545. CoffeeScript now enforces all of JavaScript's <b>Strict Mode</b> early syntax
  2546. errors at compile time. This includes old-style octal literals,
  2547. duplicate property names in object literals, duplicate parameters in
  2548. a function definition, deleting naked variables, setting the value of
  2549. <code>eval</code> or <code>arguments</code>, and more.
  2550. See a full discussion at
  2551. <a href="https://github.com/jashkenas/coffeescript/issues/1547">#1547</a>.
  2552. </li>
  2553. <li>
  2554. The REPL now has a handy new multi-line mode for entering large
  2555. blocks of code. It's useful when copy-and-pasting examples into the
  2556. REPL. Enter multi-line mode with <code>Ctrl-V</code>. You may also now
  2557. pipe input directly into the REPL.
  2558. </li>
  2559. <li>
  2560. CoffeeScript now prints a <code>Generated by CoffeeScript VERSION</code>
  2561. header at the top of each compiled file.
  2562. </li>
  2563. <li>
  2564. Conditional assignment of previously undefined variables
  2565. <code>a or= b</code> is now considered a syntax error.
  2566. </li>
  2567. <li>
  2568. A tweak to the semantics of <code>do</code>, which can now be used to
  2569. more easily simulate a namespace: <code>do (x = 1, y = 2) -> ...</code>
  2570. </li>
  2571. <li>
  2572. Loop indices are now mutable within a loop iteration, and immutable
  2573. between them.
  2574. </li>
  2575. <li>
  2576. Both endpoints of a slice are now allowed to be omitted for consistency,
  2577. effectively creating a shallow copy of the list.
  2578. </li>
  2579. <li>
  2580. Additional tweaks and improvements to <code>coffee --watch</code> under
  2581. Node's "new" file watching API. Watch will now beep by default
  2582. if you introduce a syntax error into a watched script. We also now
  2583. ignore hidden directories by default when watching recursively.
  2584. </li>
  2585. </ul>
  2586. </p>
  2587. <p>
  2588. <div class="anchor" id="1.2.0"></div>
  2589. <b class="header">
  2590. <a href="https://github.com/jashkenas/coffeescript/compare/1.1.3...1.2.0">1.2.0</a>
  2591. <span class="timestamp"> &mdash; <time datetime="2011-12-18">December 18, 2011</time></span>
  2592. </b>
  2593. <ul>
  2594. <li>
  2595. Multiple improvements to <code>coffee --watch</code> and <code>--join</code>.
  2596. You may now use both together, as well as add and remove
  2597. files and directories within a <code>--watch</code>'d folder.
  2598. </li>
  2599. <li>
  2600. The <code>throw</code> statement can now be used as part of an expression.
  2601. </li>
  2602. <li>
  2603. Block comments at the top of the file will now appear outside of the
  2604. safety closure wrapper.
  2605. </li>
  2606. <li>
  2607. Fixed a number of minor 1.1.3 regressions having to do with trailing
  2608. operators and unfinished lines, and a more major 1.1.3 regression that
  2609. caused bound functions <i>within</i> bound class functions to have the incorrect
  2610. <code>this</code>.
  2611. </li>
  2612. </ul>
  2613. </p>
  2614. <p>
  2615. <div class="anchor" id="1.1.3"></div>
  2616. <b class="header">
  2617. <a href="https://github.com/jashkenas/coffeescript/compare/1.1.2...1.1.3">1.1.3</a>
  2618. <span class="timestamp"> &mdash; <time datetime="2011-11-08">November 8, 2011</time></span>
  2619. </b>
  2620. <ul>
  2621. <li>
  2622. Ahh, whitespace. CoffeeScript's compiled JS now tries to space things
  2623. out and keep it readable, as you can see in the examples on this page.
  2624. </li>
  2625. <li>
  2626. You can now call <code>super</code> in class level methods in class bodies,
  2627. and bound class methods now preserve their correct context.
  2628. </li>
  2629. <li>
  2630. JavaScript has always supported octal numbers <code>010 is 8</code>,
  2631. and hexadecimal numbers <code>0xf is 15</code>, but CoffeeScript now
  2632. also supports binary numbers: <code>0b10 is 2</code>.
  2633. </li>
  2634. <li>
  2635. The CoffeeScript module has been nested under a subdirectory to make
  2636. it easier to <code>require</code> individual components separately, without
  2637. having to use <b>npm</b>. For example, after adding the CoffeeScript
  2638. folder to your path: <code>require('coffee-script/lexer')</code>
  2639. </li>
  2640. <li>
  2641. There's a new "link" feature in Try CoffeeScript on this webpage. Use
  2642. it to get a shareable permalink for your example script.
  2643. </li>
  2644. <li>
  2645. The <code>coffee --watch</code> feature now only works on Node.js 0.6.0
  2646. and higher, but now also works properly on Windows.
  2647. </li>
  2648. <li>
  2649. Lots of small bug fixes from
  2650. <b><a href="https://github.com/michaelficarra">@michaelficarra</a></b>,
  2651. <b><a href="https://github.com/geraldalewis">@geraldalewis</a></b>,
  2652. <b><a href="https://github.com/satyr">@satyr</a></b>, and
  2653. <b><a href="https://github.com/trevorburnham">@trevorburnham</a></b>.
  2654. </li>
  2655. </ul>
  2656. </p>
  2657. <p>
  2658. <div class="anchor" id="1.1.2"></div>
  2659. <b class="header">
  2660. <a href="https://github.com/jashkenas/coffeescript/compare/1.1.1...1.1.2">1.1.2</a>
  2661. <span class="timestamp"> &mdash; <time datetime="2011-08-04">August 4, 2011</time></span>
  2662. </b>
  2663. Fixes for block comment formatting, <code>?=</code> compilation, implicit calls
  2664. against control structures, implicit invocation of a try/catch block,
  2665. variadic arguments leaking from local scope, line numbers in syntax errors
  2666. following heregexes, property access on parenthesized number literals,
  2667. bound class methods and super with reserved names, a REPL overhaul,
  2668. consecutive compiled semicolons, block comments in implicitly called objects,
  2669. and a Chrome bug.
  2670. </p>
  2671. <p>
  2672. <div class="anchor" id="1.1.1"></div>
  2673. <b class="header">
  2674. <a href="https://github.com/jashkenas/coffeescript/compare/1.1.0...1.1.1">1.1.1</a>
  2675. <span class="timestamp"> &mdash; <time datetime="2011-05-10">May 10, 2011</time></span>
  2676. </b>
  2677. Bugfix release for classes with external constructor functions, see
  2678. issue #1182.
  2679. </p>
  2680. <p>
  2681. <div class="anchor" id="1.1.0"></div>
  2682. <b class="header">
  2683. <a href="https://github.com/jashkenas/coffeescript/compare/1.0.1...1.1.0">1.1.0</a>
  2684. <span class="timestamp"> &mdash; <time datetime="2011-05-01">May 1, 2011</time></span>
  2685. </b>
  2686. When running via the <code>coffee</code> executable, <code>process.argv</code> and
  2687. friends now report <code>coffee</code> instead of <code>node</code>.
  2688. Better compatibility with <b>Node.js 0.4.x</b> module lookup changes.
  2689. The output in the REPL is now colorized, like Node's is.
  2690. Giving your concatenated CoffeeScripts a name when using <code>--join</code> is now mandatory.
  2691. Fix for lexing compound division <code>/=</code> as a regex accidentally.
  2692. All <code>text/coffeescript</code> tags should now execute in the order they're included.
  2693. Fixed an issue with extended subclasses using external constructor functions.
  2694. Fixed an edge-case infinite loop in <code>addImplicitParentheses</code>.
  2695. Fixed exponential slowdown with long chains of function calls.
  2696. Globals no longer leak into the CoffeeScript REPL.
  2697. Splatted parameters are declared local to the function.
  2698. </p>
  2699. <p>
  2700. <div class="anchor" id="1.0.1"></div>
  2701. <b class="header">
  2702. <a href="https://github.com/jashkenas/coffeescript/compare/1.0.0...1.0.1">1.0.1</a>
  2703. <span class="timestamp"> &mdash; <time datetime="2011-01-31">January 31, 2011</time></span>
  2704. </b>
  2705. Fixed a lexer bug with Unicode identifiers. Updated REPL for compatibility
  2706. with Node.js 0.3.7. Fixed requiring relative paths in the REPL. Trailing
  2707. <code>return</code> and <code>return undefined</code> are now optimized away.
  2708. Stopped requiring the core Node.js <code>"util"</code> module for
  2709. back-compatibility with Node.js 0.2.5. Fixed a case where a
  2710. conditional <code>return</code> would cause fallthrough in a <code>switch</code>
  2711. statement. Optimized empty objects in destructuring assignment.
  2712. </p>
  2713. <p>
  2714. <div class="anchor" id="1.0.0"></div>
  2715. <b class="header">
  2716. <a href="https://github.com/jashkenas/coffeescript/compare/0.9.6...1.0.0">1.0.0</a>
  2717. <span class="timestamp"> &mdash; <time datetime="2010-12-24">December 24, 2010</time></span>
  2718. </b>
  2719. CoffeeScript loops no longer try to preserve block scope when functions
  2720. are being generated within the loop body. Instead, you can use the
  2721. <code>do</code> keyword to create a convenient closure wrapper.
  2722. Added a <code>--nodejs</code> flag for passing through options directly
  2723. to the <code>node</code> executable.
  2724. Better behavior around the use of pure statements within expressions.
  2725. Fixed inclusive slicing through <code>-1</code>, for all browsers, and splicing
  2726. with arbitrary expressions as endpoints.
  2727. </p>
  2728. <p>
  2729. <div class="anchor" id="0.9.6"></div>
  2730. <b class="header">
  2731. <a href="https://github.com/jashkenas/coffeescript/compare/0.9.5...0.9.6">0.9.6</a>
  2732. <span class="timestamp"> &mdash; <time datetime="2010-12-06">December 6, 2010</time></span>
  2733. </b>
  2734. The REPL now properly formats stacktraces, and stays alive through
  2735. asynchronous exceptions. Using <code>--watch</code> now prints timestamps as
  2736. files are compiled. Fixed some accidentally-leaking variables within
  2737. plucked closure-loops. Constructors now maintain their declaration
  2738. location within a class body. Dynamic object keys were removed.
  2739. Nested classes are now supported. Fixes execution context for naked
  2740. splatted functions. Bugfix for inversion of chained comparisons.
  2741. Chained class instantiation now works properly with splats.
  2742. </p>
  2743. <p>
  2744. <div class="anchor" id="0.9.5"></div>
  2745. <b class="header">
  2746. <a href="https://github.com/jashkenas/coffeescript/compare/0.9.4...0.9.5">0.9.5</a>
  2747. <span class="timestamp"> &mdash; <time datetime="2010-11-21">November 21, 2010</time></span>
  2748. </b>
  2749. 0.9.5 should be considered the first release candidate for CoffeeScript 1.0.
  2750. There have been a large number of internal changes since the previous release,
  2751. many contributed from <b>satyr</b>'s <a href="http://github.com/satyr/coco">Coco</a>
  2752. dialect of CoffeeScript. Heregexes (extended regexes) were added. Functions
  2753. can now have default arguments. Class bodies are now executable code.
  2754. Improved syntax errors for invalid CoffeeScript. <code>undefined</code> now
  2755. works like <code>null</code>, and cannot be assigned a new value.
  2756. There was a precedence change with respect to single-line comprehensions:
  2757. <code>result = i for i in list</code><br /> used to parse as <code>result = (i for i in list)</code>
  2758. by default ... it now parses as <br /><code>(result = i) for i in list</code>.
  2759. </p>
  2760. <p>
  2761. <div class="anchor" id="0.9.4"></div>
  2762. <b class="header">
  2763. <a href="https://github.com/jashkenas/coffeescript/compare/0.9.3...0.9.4">0.9.4</a>
  2764. <span class="timestamp"> &mdash; <time datetime="2010-09-21">September 21, 2010</time></span>
  2765. </b>
  2766. CoffeeScript now uses appropriately-named temporary variables, and recycles
  2767. their references after use. Added <code>require.extensions</code> support for
  2768. <b>Node.js 0.3</b>. Loading CoffeeScript in the browser now adds just a
  2769. single <code>CoffeeScript</code> object to global scope.
  2770. Fixes for implicit object and block comment edge cases.
  2771. </p>
  2772. <p>
  2773. <div class="anchor" id="0.9.3"></div>
  2774. <b class="header">
  2775. <a href="https://github.com/jashkenas/coffeescript/compare/0.9.2...0.9.3">0.9.3</a>
  2776. <span class="timestamp"> &mdash; <time datetime="2010-09-16">September 16, 2010</time></span>
  2777. </b>
  2778. CoffeeScript <code>switch</code> statements now compile into JS <code>switch</code>
  2779. statements &mdash; they previously compiled into <code>if/else</code> chains
  2780. for JavaScript 1.3 compatibility.
  2781. Soaking a function invocation is now supported. Users of the RubyMine
  2782. editor should now be able to use <code>--watch</code> mode.
  2783. </p>
  2784. <p>
  2785. <div class="anchor" id="0.9.2"></div>
  2786. <b class="header">
  2787. <a href="https://github.com/jashkenas/coffeescript/compare/0.9.1...0.9.2">0.9.2</a>
  2788. <span class="timestamp"> &mdash; <time datetime="2010-08-23">August 23, 2010</time></span>
  2789. </b>
  2790. Specifying the start and end of a range literal is now optional, eg. <code>array[3..]</code>.
  2791. You can now say <code>a not instanceof b</code>.
  2792. Fixed important bugs with nested significant and non-significant indentation (Issue #637).
  2793. Added a <code>--require</code> flag that allows you to hook into the <code>coffee</code> command.
  2794. Added a custom <code>jsl.conf</code> file for our preferred JavaScriptLint setup.
  2795. Sped up Jison grammar compilation time by flattening rules for operations.
  2796. Block comments can now be used with JavaScript-minifier-friendly syntax.
  2797. Added JavaScript's compound assignment bitwise operators. Bugfixes to
  2798. implicit object literals with leading number and string keys, as the subject
  2799. of implicit calls, and as part of compound assignment.
  2800. </p>
  2801. <p>
  2802. <div class="anchor" id="0.9.1"></div>
  2803. <b class="header">
  2804. <a href="https://github.com/jashkenas/coffeescript/compare/0.9.0...0.9.1">0.9.1</a>
  2805. <span class="timestamp"> &mdash; <time datetime="2010-08-11">August 11, 2010</time></span>
  2806. </b>
  2807. Bugfix release for <b>0.9.1</b>. Greatly improves the handling of mixed
  2808. implicit objects, implicit function calls, and implicit indentation.
  2809. String and regex interpolation is now strictly <code>#{ ... }</code> (Ruby style).
  2810. The compiler now takes a <code>--require</code> flag, which specifies scripts
  2811. to run before compilation.
  2812. </p>
  2813. <p>
  2814. <div class="anchor" id="0.9.0"></div>
  2815. <b class="header">
  2816. <a href="https://github.com/jashkenas/coffeescript/compare/0.7.2...0.9.0">0.9.0</a>
  2817. <span class="timestamp"> &mdash; <time datetime="2010-08-04">August 4, 2010</time></span>
  2818. </b>
  2819. The CoffeeScript <b>0.9</b> series is considered to be a release candidate
  2820. for <b>1.0</b>; let's give her a shakedown cruise. <b>0.9.0</b> introduces a massive
  2821. backwards-incompatible change: Assignment now uses <code>=</code>, and object
  2822. literals use <code>:</code>, as in JavaScript. This allows us to have implicit
  2823. object literals, and YAML-style object definitions. Half assignments are
  2824. removed, in favor of <code>+=</code>, <code>or=</code>, and friends.
  2825. Interpolation now uses a hash mark <code>#</code> instead of the dollar sign
  2826. <code>$</code> &mdash; because dollar signs may be part of a valid JS identifier.
  2827. Downwards range comprehensions are now safe again, and are optimized to
  2828. straight for loops when created with integer endpoints.
  2829. A fast, unguarded form of object comprehension was added:
  2830. <code>for all key, value of object</code>. Mentioning the <code>super</code> keyword
  2831. with no arguments now forwards all arguments passed to the function,
  2832. as in Ruby. If you extend class <code>B</code> from parent class <code>A</code>, if
  2833. <code>A</code> has an <code>extended</code> method defined, it will be called, passing in <code>B</code> &mdash;
  2834. this enables static inheritance, among other things. Cleaner output for
  2835. functions bound with the fat arrow. <code>@variables</code> can now be used
  2836. in parameter lists, with the parameter being automatically set as a property
  2837. on the object &mdash; useful in constructors and setter functions.
  2838. Constructor functions can now take splats.
  2839. </p>
  2840. <p>
  2841. <div class="anchor" id="0.7.2"></div>
  2842. <b class="header">
  2843. <a href="https://github.com/jashkenas/coffeescript/compare/0.7.1...0.7.2">0.7.2</a>
  2844. <span class="timestamp"> &mdash; <time datetime="2010-07-12">July 12, 2010</time></span>
  2845. </b>
  2846. Quick bugfix (right after 0.7.1) for a problem that prevented <code>coffee</code>
  2847. command-line options from being parsed in some circumstances.
  2848. </p>
  2849. <p>
  2850. <div class="anchor" id="0.7.1"></div>
  2851. <b class="header">
  2852. <a href="https://github.com/jashkenas/coffeescript/compare/0.7.0...0.7.1">0.7.1</a>
  2853. <span class="timestamp"> &mdash; <time datetime="2010-07-11">July 11, 2010</time></span>
  2854. </b>
  2855. Block-style comments are now passed through and printed as JavaScript block
  2856. comments -- making them useful for licenses and copyright headers. Better
  2857. support for running coffee scripts standalone via hashbangs.
  2858. Improved syntax errors for tokens that are not in the grammar.
  2859. </p>
  2860. <p>
  2861. <div class="anchor" id="0.7.0"></div>
  2862. <b class="header">
  2863. <a href="https://github.com/jashkenas/coffeescript/compare/0.6.2...0.7.0">0.7.0</a>
  2864. <span class="timestamp"> &mdash; <time datetime="2010-06-28">June 28, 2010</time></span>
  2865. </b>
  2866. Official CoffeeScript variable style is now camelCase, as in JavaScript.
  2867. Reserved words are now allowed as object keys, and will be quoted for you.
  2868. Range comprehensions now generate cleaner code, but you have to specify <code>by -1</code>
  2869. if you'd like to iterate downward. Reporting of syntax errors is greatly
  2870. improved from the previous release. Running <code>coffee</code> with no arguments
  2871. now launches the REPL, with Readline support. The <code>&lt;-</code> bind operator
  2872. has been removed from CoffeeScript. The <code>loop</code> keyword was added,
  2873. which is equivalent to a <code>while true</code> loop. Comprehensions that contain
  2874. closures will now close over their variables, like the semantics of a <code>forEach</code>.
  2875. You can now use bound function in class definitions (bound to the instance).
  2876. For consistency, <code>a in b</code> is now an array presence check, and <code>a of b</code>
  2877. is an object-key check. Comments are no longer passed through to the generated
  2878. JavaScript.
  2879. </p>
  2880. <p>
  2881. <div class="anchor" id="0.6.2"></div>
  2882. <b class="header">
  2883. <a href="https://github.com/jashkenas/coffeescript/compare/0.6.1...0.6.2">0.6.2</a>
  2884. <span class="timestamp"> &mdash; <time datetime="2010-05-15">May 15, 2010</time></span>
  2885. </b>
  2886. The <code>coffee</code> command will now preserve directory structure when
  2887. compiling a directory full of scripts. Fixed two omissions that were preventing
  2888. the CoffeeScript compiler from running live within Internet Explorer.
  2889. There's now a syntax for block comments, similar in spirit to CoffeeScript's heredocs.
  2890. ECMA Harmony DRY-style pattern matching is now supported, where the name
  2891. of the property is the same as the name of the value: <code>{name, length}: func</code>.
  2892. Pattern matching is now allowed within comprehension variables. <code>unless</code>
  2893. is now allowed in block form. <code>until</code> loops were added, as the inverse
  2894. of <code>while</code> loops. <code>switch</code> statements are now allowed without
  2895. switch object clauses. Compatible
  2896. with Node.js <b>v0.1.95</b>.
  2897. </p>
  2898. <p>
  2899. <div class="anchor" id="0.6.1"></div>
  2900. <b class="header">
  2901. <a href="https://github.com/jashkenas/coffeescript/compare/0.6.0...0.6.1">0.6.1</a>
  2902. <span class="timestamp"> &mdash; <time datetime="2010-04-12">April 12, 2010</time></span>
  2903. </b>
  2904. Upgraded CoffeeScript for compatibility with the new Node.js <b>v0.1.90</b>
  2905. series.
  2906. </p>
  2907. <p>
  2908. <div class="anchor" id="0.6.0"></div>
  2909. <b class="header">
  2910. <a href="https://github.com/jashkenas/coffeescript/compare/0.5.6...0.6.0">0.6.0</a>
  2911. <span class="timestamp"> &mdash; <time datetime="2010-04-03">April 3, 2010</time></span>
  2912. </b>
  2913. Trailing commas are now allowed, a-la Python. Static
  2914. properties may be assigned directly within class definitions,
  2915. using <code>@property</code> notation.
  2916. </p>
  2917. <p>
  2918. <div class="anchor" id="0.5.6"></div>
  2919. <b class="header">
  2920. <a href="https://github.com/jashkenas/coffeescript/compare/0.5.5...0.5.6">0.5.6</a>
  2921. <span class="timestamp"> &mdash; <time datetime="2010-03-23">March 23, 2010</time></span>
  2922. </b>
  2923. Interpolation can now be used within regular expressions and heredocs, as well as
  2924. strings. Added the <code>&lt;-</code> bind operator.
  2925. Allowing assignment to half-expressions instead of special <code>||=</code>-style
  2926. operators. The arguments object is no longer automatically converted into
  2927. an array. After requiring <code>coffee-script</code>, Node.js can now directly
  2928. load <code>.coffee</code> files, thanks to <b>registerExtension</b>. Multiple
  2929. splats can now be used in function calls, arrays, and pattern matching.
  2930. </p>
  2931. <p>
  2932. <div class="anchor" id="0.5.5"></div>
  2933. <b class="header">
  2934. <a href="https://github.com/jashkenas/coffeescript/compare/0.5.4...0.5.5">0.5.5</a>
  2935. <span class="timestamp"> &mdash; <time datetime="2010-03-08">March 8, 2010</time></span>
  2936. </b>
  2937. String interpolation, contributed by
  2938. <a href="http://github.com/StanAngeloff">Stan Angeloff</a>.
  2939. Since <code>--run</code> has been the default since <b>0.5.3</b>, updating
  2940. <code>--stdio</code> and <code>--eval</code> to run by default, pass <code>--compile</code>
  2941. as well if you'd like to print the result.
  2942. </p>
  2943. <p>
  2944. <div class="anchor" id="0.5.4"></div>
  2945. <b class="header">
  2946. <a href="https://github.com/jashkenas/coffeescript/compare/0.5.3...0.5.4">0.5.4</a>
  2947. <span class="timestamp"> &mdash; <time datetime="2010-03-03">March 3, 2010</time></span>
  2948. </b>
  2949. Bugfix that corrects the Node.js global constants <code>__filename</code> and
  2950. <code>__dirname</code>. Tweaks for more flexible parsing of nested function
  2951. literals and improperly-indented comments. Updates for the latest Node.js API.
  2952. </p>
  2953. <p>
  2954. <div class="anchor" id="0.5.3"></div>
  2955. <b class="header">
  2956. <a href="https://github.com/jashkenas/coffeescript/compare/0.5.2...0.5.3">0.5.3</a>
  2957. <span class="timestamp"> &mdash; <time datetime="2010-02-27">February 27, 2010</time></span>
  2958. </b>
  2959. CoffeeScript now has a syntax for defining classes. Many of the core
  2960. components (Nodes, Lexer, Rewriter, Scope, Optparse) are using them.
  2961. Cakefiles can use <code>optparse.coffee</code> to define options for tasks.
  2962. <code>--run</code> is now the default flag for the <code>coffee</code> command,
  2963. use <code>--compile</code> to save JavaScripts. Bugfix for an ambiguity between
  2964. RegExp literals and chained divisions.
  2965. </p>
  2966. <p>
  2967. <div class="anchor" id="0.5.2"></div>
  2968. <b class="header">
  2969. <a href="https://github.com/jashkenas/coffeescript/compare/0.5.1...0.5.2">0.5.2</a>
  2970. <span class="timestamp"> &mdash; <time datetime="2010-02-25">February 25, 2010</time></span>
  2971. </b>
  2972. Added a compressed version of the compiler for inclusion in web pages as
  2973. <br /><code>extras/coffee-script.js</code>. It'll automatically run any script tags
  2974. with type <code>text/coffeescript</code> for you. Added a <code>--stdio</code> option
  2975. to the <code>coffee</code> command, for piped-in compiles.
  2976. </p>
  2977. <p>
  2978. <div class="anchor" id="0.5.1"></div>
  2979. <b class="header">
  2980. <a href="https://github.com/jashkenas/coffeescript/compare/0.5.0...0.5.1">0.5.1</a>
  2981. <span class="timestamp"> &mdash; <time datetime="2010-02-24">February 24, 2010</time></span>
  2982. </b>
  2983. Improvements to null soaking with the existential operator, including
  2984. soaks on indexed properties. Added conditions to <code>while</code> loops,
  2985. so you can use them as filters with <code>when</code>, in the same manner as
  2986. comprehensions.
  2987. </p>
  2988. <p>
  2989. <div class="anchor" id="0.5.0"></div>
  2990. <b class="header">
  2991. <a href="https://github.com/jashkenas/coffeescript/compare/0.3.2...0.5.0">0.5.0</a>
  2992. <span class="timestamp"> &mdash; <time datetime="2010-02-21">February 21, 2010</time></span>
  2993. </b>
  2994. CoffeeScript 0.5.0 is a major release, While there are no language changes,
  2995. the Ruby compiler has been removed in favor of a self-hosting
  2996. compiler written in pure CoffeeScript.
  2997. </p>
  2998. <p>
  2999. <div class="anchor" id="0.3.2"></div>
  3000. <b class="header">
  3001. <a href="https://github.com/jashkenas/coffeescript/compare/0.3.0...0.3.2">0.3.2</a>
  3002. <span class="timestamp"> &mdash; <time datetime="2010-02-08">February 8, 2010</time></span>
  3003. </b>
  3004. <code>@property</code> is now a shorthand for <code>this.property</code>.<br />
  3005. Switched the default JavaScript engine from Narwhal to Node.js. Pass
  3006. the <code>--narwhal</code> flag if you'd like to continue using it.
  3007. </p>
  3008. <p>
  3009. <div class="anchor" id="0.3.0"></div>
  3010. <b class="header">
  3011. <a href="https://github.com/jashkenas/coffeescript/compare/0.2.6...0.3.0">0.3.0</a>
  3012. <span class="timestamp"> &mdash; <time datetime="2010-01-26">January 26, 2010</time></span>
  3013. </b>
  3014. CoffeeScript 0.3 includes major syntax changes:
  3015. <br />
  3016. The function symbol was changed to
  3017. <code>-></code>, and the bound function symbol is now <code>=></code>.
  3018. <br />
  3019. Parameter lists in function definitions must now be wrapped in parentheses.
  3020. <br />
  3021. Added property soaking, with the <code>?.</code> operator.
  3022. <br />
  3023. Made parentheses optional, when invoking functions with arguments.
  3024. <br />
  3025. Removed the obsolete block literal syntax.
  3026. </p>
  3027. <p>
  3028. <div class="anchor" id="0.2.6"></div>
  3029. <b class="header">
  3030. <a href="https://github.com/jashkenas/coffeescript/compare/0.2.5...0.2.6">0.2.6</a>
  3031. <span class="timestamp"> &mdash; <time datetime="2010-01-17">January 17, 2010</time></span>
  3032. </b>
  3033. Added Python-style chained comparisons, the conditional existence
  3034. operator <code>?=</code>, and some examples from <i>Beautiful Code</i>.
  3035. Bugfixes relating to statement-to-expression conversion, arguments-to-array
  3036. conversion, and the TextMate syntax highlighter.
  3037. </p>
  3038. <p>
  3039. <div class="anchor" id="0.2.5"></div>
  3040. <b class="header">
  3041. <a href="https://github.com/jashkenas/coffeescript/compare/0.2.4...0.2.5">0.2.5</a>
  3042. <span class="timestamp"> &mdash; <time datetime="2010-01-13">January 13, 2010</time></span>
  3043. </b>
  3044. The conditions in switch statements can now take multiple values at once &mdash;
  3045. If any of them are true, the case will run. Added the long arrow <code>==></code>,
  3046. which defines and immediately binds a function to <code>this</code>. While loops can
  3047. now be used as expressions, in the same way that comprehensions can. Splats
  3048. can be used within pattern matches to soak up the rest of an array.
  3049. </p>
  3050. <p>
  3051. <div class="anchor" id="0.2.4"></div>
  3052. <b class="header">
  3053. <a href="https://github.com/jashkenas/coffeescript/compare/0.2.3...0.2.4">0.2.4</a>
  3054. <span class="timestamp"> &mdash; <time datetime="2010-01-12">January 12, 2010</time></span>
  3055. </b>
  3056. Added ECMAScript Harmony style destructuring assignment, for dealing with
  3057. extracting values from nested arrays and objects. Added indentation-sensitive
  3058. heredocs for nicely formatted strings or chunks of code.
  3059. </p>
  3060. <p>
  3061. <div class="anchor" id="0.2.3"></div>
  3062. <b class="header">
  3063. <a href="https://github.com/jashkenas/coffeescript/compare/0.2.2...0.2.3">0.2.3</a>
  3064. <span class="timestamp"> &mdash; <time datetime="2010-01-11">January 11, 2010</time></span>
  3065. </b>
  3066. Axed the unsatisfactory <code>ino</code> keyword, replacing it with <code>of</code> for
  3067. object comprehensions. They now look like: <code>for prop, value of object</code>.
  3068. </p>
  3069. <p>
  3070. <div class="anchor" id="0.2.2"></div>
  3071. <b class="header">
  3072. <a href="https://github.com/jashkenas/coffeescript/compare/0.2.1...0.2.2">0.2.2</a>
  3073. <span class="timestamp"> &mdash; <time datetime="2010-01-10">January 10, 2010</time></span>
  3074. </b>
  3075. When performing a comprehension over an object, use <code>ino</code>, instead
  3076. of <code>in</code>, which helps us generate smaller, more efficient code at
  3077. compile time.
  3078. <br />
  3079. Added <code>::</code> as a shorthand for saying <code>.prototype.</code>
  3080. <br />
  3081. The "splat" symbol has been changed from a prefix asterisk <code>*</code>, to
  3082. a postfix ellipsis <code>...</code>
  3083. <br />
  3084. Added JavaScript's <code>in</code> operator,
  3085. empty <code>return</code> statements, and empty <code>while</code> loops.
  3086. <br />
  3087. Constructor functions that start with capital letters now include a
  3088. safety check to make sure that the new instance of the object is returned.
  3089. <br />
  3090. The <code>extends</code> keyword now functions identically to <code>goog.inherits</code>
  3091. in Google's Closure Library.
  3092. </p>
  3093. <p>
  3094. <div class="anchor" id="0.2.1"></div>
  3095. <b class="header">
  3096. <a href="https://github.com/jashkenas/coffeescript/compare/0.2.0...0.2.1">0.2.1</a>
  3097. <span class="timestamp"> &mdash; <time datetime="2010-01-05">January 5, 2010</time></span>
  3098. </b>
  3099. Arguments objects are now converted into real arrays when referenced.
  3100. </p>
  3101. <p>
  3102. <div class="anchor" id="0.2.0"></div>
  3103. <b class="header">
  3104. <a href="https://github.com/jashkenas/coffeescript/compare/0.1.6...0.2.0">0.2.0</a>
  3105. <span class="timestamp"> &mdash; <time datetime="2010-01-05">January 5, 2010</time></span>
  3106. </b>
  3107. Major release. Significant whitespace. Better statement-to-expression
  3108. conversion. Splats. Splice literals. Object comprehensions. Blocks.
  3109. The existential operator. Many thanks to all the folks who posted issues,
  3110. with special thanks to
  3111. <a href="http://github.com/liamoc">Liam O'Connor-Davis</a> for whitespace
  3112. and expression help.
  3113. </p>
  3114. <p>
  3115. <div class="anchor" id="0.1.6"></div>
  3116. <b class="header">
  3117. <a href="https://github.com/jashkenas/coffeescript/compare/0.1.5...0.1.6">0.1.6</a>
  3118. <span class="timestamp"> &mdash; <time datetime="2009-12-27">December 27, 2009</time></span>
  3119. </b>
  3120. Bugfix for running <code>coffee --interactive</code> and <code>--run</code>
  3121. from outside of the CoffeeScript directory. Bugfix for nested
  3122. function/if-statements.
  3123. </p>
  3124. <p>
  3125. <div class="anchor" id="0.1.5"></div>
  3126. <b class="header">
  3127. <a href="https://github.com/jashkenas/coffeescript/compare/0.1.4...0.1.5">0.1.5</a>
  3128. <span class="timestamp"> &mdash; <time datetime="2009-12-26">December 26, 2009</time></span>
  3129. </b>
  3130. Array slice literals and array comprehensions can now both take Ruby-style
  3131. ranges to specify the start and end. JavaScript variable declaration is
  3132. now pushed up to the top of the scope, making all assignment statements into
  3133. expressions. You can use <code>\</code> to escape newlines.
  3134. The <code>coffee-script</code> command is now called <code>coffee</code>.
  3135. </p>
  3136. <p>
  3137. <div class="anchor" id="0.1.4"></div>
  3138. <b class="header">
  3139. <a href="https://github.com/jashkenas/coffeescript/compare/0.1.3...0.1.4">0.1.4</a>
  3140. <span class="timestamp"> &mdash; <time datetime="2009-12-25">December 25, 2009</time></span>
  3141. </b>
  3142. The official CoffeeScript extension is now <code>.coffee</code> instead of
  3143. <code>.cs</code>, which properly belongs to
  3144. <a href="http://en.wikipedia.org/wiki/C_Sharp_(programming_language)">C#</a>.
  3145. Due to popular demand, you can now also use <code>=</code> to assign. Unlike
  3146. JavaScript, <code>=</code> can also be used within object literals, interchangeably
  3147. with <code>:</code>. Made a grammatical fix for chained function calls
  3148. like <code>func(1)(2)(3)(4)</code>. Inheritance and super no longer use
  3149. <code>__proto__</code>, so they should be IE-compatible now.
  3150. </p>
  3151. <p>
  3152. <div class="anchor" id="0.1.3"></div>
  3153. <b class="header">
  3154. <a href="https://github.com/jashkenas/coffeescript/compare/0.1.2...0.1.3">0.1.3</a>
  3155. <span class="timestamp"> &mdash; <time datetime="2009-12-25">December 25, 2009</time></span>
  3156. </b>
  3157. The <code>coffee</code> command now includes <code>--interactive</code>,
  3158. which launches an interactive CoffeeScript session, and <code>--run</code>,
  3159. which directly compiles and executes a script. Both options depend on a
  3160. working installation of Narwhal.
  3161. The <code>aint</code> keyword has been replaced by <code>isnt</code>, which goes
  3162. together a little smoother with <code>is</code>.
  3163. Quoted strings are now allowed as identifiers within object literals: eg.
  3164. <code>{"5+5": 10}</code>.
  3165. All assignment operators now use a colon: <code>+:</code>, <code>-:</code>,
  3166. <code>*:</code>, etc.
  3167. </p>
  3168. <p>
  3169. <div class="anchor" id="0.1.2"></div>
  3170. <b class="header">
  3171. <a href="https://github.com/jashkenas/coffeescript/compare/0.1.1...0.1.2">0.1.2</a>
  3172. <span class="timestamp"> &mdash; <time datetime="2009-12-24">December 24, 2009</time></span>
  3173. </b>
  3174. Fixed a bug with calling <code>super()</code> through more than one level of
  3175. inheritance, with the re-addition of the <code>extends</code> keyword.
  3176. Added experimental <a href="http://narwhaljs.org/">Narwhal</a>
  3177. support (as a Tusk package), contributed by
  3178. <a href="http://tlrobinson.net/">Tom Robinson</a>, including
  3179. <b>bin/cs</b> as a CoffeeScript REPL and interpreter.
  3180. New <code>--no-wrap</code> option to suppress the safety function
  3181. wrapper.
  3182. </p>
  3183. <p>
  3184. <div class="anchor" id="0.1.1"></div>
  3185. <b class="header">
  3186. <a href="https://github.com/jashkenas/coffeescript/compare/0.1.0...0.1.1">0.1.1</a>
  3187. <span class="timestamp"> &mdash; <time datetime="2009-12-24">December 24, 2009</time></span>
  3188. </b>
  3189. Added <code>instanceof</code> and <code>typeof</code> as operators.
  3190. </p>
  3191. <p>
  3192. <div class="anchor" id="0.1.0"></div>
  3193. <b class="header">
  3194. 0.1.0
  3195. <span class="timestamp"> &mdash; <time datetime="2009-12-24">December 24, 2009</time></span>
  3196. </b>
  3197. Initial CoffeeScript release.
  3198. </p>
  3199. </div>
  3200. <script type="text/coffeescript">
  3201. sourceFragment = "try:"
  3202. # Set up the compilation function, to run when you stop typing.
  3203. compileSource = ->
  3204. source = $('#repl_source').val()
  3205. results = $('#repl_results')
  3206. window.compiledJS = ''
  3207. try
  3208. window.compiledJS = CoffeeScript.compile source, bare: on
  3209. el = results[0]
  3210. if el.innerText
  3211. el.innerText = window.compiledJS
  3212. else
  3213. results.text(window.compiledJS)
  3214. results.removeClass 'error'
  3215. $('.minibutton.run').removeClass 'error'
  3216. catch {location, message}
  3217. if location?
  3218. message = "Error on line #{location.first_line + 1}: #{message}"
  3219. results.text(message).addClass 'error'
  3220. $('.minibutton.run').addClass 'error'
  3221. # Update permalink
  3222. $('#repl_permalink').attr 'href', "##{sourceFragment}#{encodeURIComponent source}"
  3223. # Listen for keypresses and recompile.
  3224. $('#repl_source').keyup -> compileSource()
  3225. # Eval the compiled js.
  3226. evalJS = ->
  3227. try
  3228. eval window.compiledJS
  3229. catch error then alert error
  3230. # Load the console with a string of CoffeeScript.
  3231. window.loadConsole = (coffee) ->
  3232. $('#repl_source').val coffee
  3233. compileSource()
  3234. $('.navigation.try').addClass('active')
  3235. false
  3236. # Helper to hide the menus.
  3237. closeMenus = ->
  3238. $('.navigation.active').removeClass 'active'
  3239. $('.minibutton.run').click -> evalJS()
  3240. # Bind navigation buttons to open the menus.
  3241. $('.navigation').click (e) ->
  3242. return if e.target.tagName.toLowerCase() is 'a'
  3243. return false if $(e.target).closest('.repl_wrapper').length
  3244. if $(this).hasClass('active')
  3245. closeMenus()
  3246. else
  3247. closeMenus()
  3248. $(this).addClass 'active'
  3249. false
  3250. # Dismiss console if Escape pressed or click falls outside console
  3251. # Trigger Run button on Ctrl-Enter
  3252. $(document.body)
  3253. .keydown (e) ->
  3254. closeMenus() if e.which == 27
  3255. evalJS() if e.which == 13 and (e.metaKey or e.ctrlKey) and $('.minibutton.run:visible').length
  3256. .click (e) ->
  3257. return false if $(e.target).hasClass('minibutton')
  3258. closeMenus()
  3259. $('#open_webchat').click ->
  3260. $(this).replaceWith $('<iframe src="http://webchat.freenode.net/?channels=coffeescript" width="625" height="400"></iframe>')
  3261. $("#repl_permalink").click (e) ->
  3262. window.location = $(this).attr("href")
  3263. false
  3264. # If source code is included in location.hash, display it.
  3265. hash = decodeURIComponent location.hash.replace(/^#/, '')
  3266. if hash.indexOf(sourceFragment) == 0
  3267. src = hash.substr sourceFragment.length
  3268. loadConsole src
  3269. compileSource()
  3270. </script>
  3271. <script src="documentation/vendor/jquery-1.6.4.js"></script>
  3272. <script src="extras/coffee-script.js"></script>
  3273. </body>
  3274. </html>