jashkenas--coffeescript/docs/v2/index.html

6407 lines
437 KiB
HTML
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=UTF-8" />
<title>CoffeeScript</title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="canonical" href="https://coffeescript.org" />
<link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png">
<link rel="icon" type="image/png" href="/favicon-32x32.png" sizes="32x32">
<link rel="icon" type="image/png" href="/favicon-16x16.png" sizes="16x16">
<link rel="manifest" href="/manifest.json">
<link rel="mask-icon" href="/safari-pinned-tab.svg" color="#5bbad5">
<meta name="theme-color" content="#ffffff">
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" crossorigin="anonymous">
<!-- The CoffeeScript logo font is Googles Galada -->
<link href="https://fonts.googleapis.com/css?family=Alegreya+Sans:400,800|Lato:300,300i,400,700|Roboto+Mono:400,400i" rel="stylesheet" crossorigin="anonymous">
<link href="https://cdn.jsdelivr.net/npm/codemirror@5.37.0/lib/codemirror.css" rel="stylesheet" crossorigin="anonymous">
<style>
/* Adapted from https://github.com/FarhadG/code-mirror-themes/blob/master/themes/twilight.css and https://github.com/codemirror/CodeMirror/blob/master/theme/twilight.css */
/* CodeMirror general styling */
.CodeMirror,
.placeholder-code {
/* https://codemirror.net/demo/resize.html */
height: auto;
background: transparent;
font-family: 'Roboto Mono';
font-weight: 400;
line-height: 1.25;
letter-spacing: 0.3px;
color: #f8f8f8;
/* Prevent mobile Safari from zooming in on our code editors; the code is 16px naturally, but somehow being explicit about it prevents the zooming */
font-size: 16px;
}
@media (min-width: 768px) {
.CodeMirror,
.placeholder-code {
font-size: 87.5%; /* Matching Bootstraps font size for code, which calculates to 14.4px */
}
}
.CodeMirror-lines {
padding: 0.5em 0;
}
.placeholder-code {
padding: 0.5em 4px;
margin-bottom: 1.37em;
white-space: pre-wrap;
}
.CodeMirror pre,
pre.placeholder-code {
line-height: 1.4em;
}
.CodeMirror-code:focus {
outline: none;
}
div.CodeMirror-cursor {
border-left: 3px solid #f8f8f8;
}
.CodeMirror-activeline-background {
background: #ffffff08;
}
.CodeMirror-selected {
background: #ddf0ff33;
}
/* Syntax highlighting */
.cm-keyword,
.placeholder-code .keyword {
color: #cda869;
}
.cm-atom {
color: #dad085;
}
.cm-number,
.cm-meta,
.placeholder-code .number,
.placeholder-code .built_in,
.placeholder-code .builtin-name,
.placeholder-code .literal,
.placeholder-code .type,
/*.placeholder-code .params,*/
.placeholder-code .meta,
.placeholder-code .link {
color: #dad085;
}
.cm-def {
color: #f8f8f8;
}
span.cm-variable-2,
span.cm-tag {
color: #f8f8f8;
}
span.cm-variable-3,
span.cm-def,
span.cm-type {
color: #f8f8f8;
}
.cm-operator,
.placeholder-code .punctuation,
.placeholder-code .symbol,
.placeholder-code .bullet,
.placeholder-code .addition,
.placeholder-code .operator {
color: #cda869;
}
.cm-comment,
.placeholder-code .comment {
font-style: italic;
color: #5f5a60;
}
.cm-string,
.cm-string-2,
.placeholder-code .string {
color: #8f9d6a;
}
.cm-property,
.placeholder-code .attribute {
color: #dad085;
}
.cm-builtin {
color: #cda869;
}
.cm-tag {
color: #997643;
}
.cm-attribute {
color: #d6bb6d;
}
.cm-header {
color: #FF6400;
}
.cm-hr {
color: #AEAEAE;
}
.cm-link {
color: #ad9361;
font-style: italic;
text-decoration: none;
}
.cm-error {
border-bottom: 1px solid rgba(142, 22, 22, 0.67);
}
/* Uneditable code blocks are inverted, so use darker versions of the above */
.uneditable-code-block code {
padding: 0;
}
.uneditable-code-block .comment {
font-style: italic;
color: #837B85;
}
.uneditable-code-block .class,
.uneditable-code-block .function,
.uneditable-code-block .keyword,
.uneditable-code-block .reserved,
.uneditable-code-block .title {
color: #534328;
}
.uneditable-code-block .string
.uneditable-code-block .value
.uneditable-code-block .inheritance
.uneditable-code-block .header {
color: #3A4029;
}
.uneditable-code-block .variable,
.uneditable-code-block .literal,
.uneditable-code-block .tag,
.uneditable-code-block .regexp,
.uneditable-code-block .subst,
.uneditable-code-block .property {
color: #474429;
}
.uneditable-code-block .number,
.uneditable-code-block .preprocessor,
.uneditable-code-block .built_in,
.uneditable-code-block .params,
.uneditable-code-block .constant {
color: #474429;
}
html,
body {
/* Prevent scroll on narrow devices */
overflow-x: hidden;
}
body {
/* Required for Scrollspy */
position: relative;
/* Push below header bar */
margin-top: 3.5rem;
}
svg {
width: auto;
height: 100%;
}
a {
color: #1b5e20;
transition: 0.1s ease-in-out;
}
a:focus, a:hover, a:active {
color: #388e3c;
cursor: pointer;
text-decoration: none;
}
button:focus, .navbar-dark .navbar-toggler:focus {
outline: none;
border: thin solid rgba(248, 243, 240, 0.3);
}
.bg-dark {
background-color: #3e2723 !important;
}
.bg-ribbed-light {
background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1 3"><path opacity=".03" fill="#000" d="M0 0h1v1H0z"/><path opacity=".005" fill="#000" d="M0 1h1v2H0z"/></svg>');
background-size: 1px 3px;
}
.bg-ribbed-dark {
background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1 3"><path opacity=".2" fill="#000" d="M0 0h1v1H0z"/><path opacity=".15" fill="#000" d="M0 1h1v2H0z"/></svg>');
background-size: 1px 3px;
}
/*
* Header
*/
.site-navbar {
height: 3.5rem;
font-family: 'Lato';
font-weight: 400;
font-size: 1.1em;
}
.navbar-brand {
height: 2.2em;
margin-right: 1em;
}
.navbar-dark path {
fill: #fff;
}
.navbar-nav .nav-item {
margin-left: 0.6em;
margin-right: 0.6em;
border-radius: 0.4em;
}
.navbar-nav .nav-item:hover,
.navbar-nav .nav-item:active,
.navbar-nav .nav-item.show {
background-color: #4e342e;
}
.navbar-toggler {
transition: all 0.1s ease-in-out;
}
/*
* Layout; based on https://codepen.io/Sphinxxxx/pen/WjwbEO
*/
.main-row {
height: calc(100vh - 3.5rem);
}
/*
* Sidebar
*/
.sidebar {
/* Scrollable contents if viewport is shorter than content */
overflow-y: auto;
overflow-x: hidden;
left: 0;
bottom: 0;
z-index: 1000;
padding: 0;
background-color: #efebe9;
border-right: 1px solid #efebe9;
}
.sidebar::-webkit-scrollbar {
display: none;
}
@media screen and (max-width: 991px) {
.sidebar {
position: fixed;
top: 3.5em;
height: calc(100% - 3.5rem);
left: -100%;
transition: 0.25s left ease-in-out;
}
.sidebar.show {
left: 0;
}
}
@media (min-width: 992px) {
.sidebar {
flex: 0 0 auto;
}
}
.contents {
padding: 0.5em 0 0.5em 0.5em;
font-family: 'Alegreya Sans';
font-weight: 400;
font-size: 1.2em;
align-items: normal;
}
.contents .nav .nav {
margin-left: 1em;
font-size: 0.9em;
}
.contents .nav-link {
padding: 0.2em 0.7em;
}
.contents .nav-link.active,
.contents .nav-link.active a:hover,
.contents .nav-link.active a:focus {
font-weight: 800;
}
/*
* Main content
*/
.main {
max-width: 100%;
padding: 1.3em;
}
@media (min-width: 992px) {
.main {
flex: 1 1 auto;
overflow: auto;
padding-right: 2em;
padding-left: 2em;
}
}
.title-logo {
width: 30rem;
margin: 3rem auto;
}
.title-logo path {
fill: #2f2625;
}
.main p, .main li, .main td, .main th {
font-family: Lato;
font-weight: 300;
font-size: 1.1em;
line-height: 1.7;
}
.main blockquote {
font-size: 1.1em;
}
.main li p, .main li li, .main li blockquote {
font-size: 1em;
}
@media (min-width: 768px) {
.main p, .main li, .main td, .main th, .main blockquote {
font-size: 1.2em;
}
}
.main td {
vertical-align: top;
padding: 0.3em 0;
}
.main strong, .main th {
font-weight: 700;
}
.main a {
border-bottom: 2px solid transparent;
font-weight: 400;
}
.main a:focus, .main a:hover, .main a:active {
border-bottom: 2px solid rgba(56, 142, 60, 0.2);
}
.main blockquote pre {
background-color: #f8f3f0;
color: #2f2625;
border-radius: .3em;
padding: 0.4em 0.6em;
}
p, blockquote, table, .code-example {
margin-bottom: 1.1em;
}
.main li {
margin-bottom: 0.6em;
}
code, td code {
white-space: nowrap;
padding: 2px 8px;
}
pre code {
white-space: pre; /* We want newlines to be newlines in code blocks */
}
h2, h3, h4 {
margin-top: 1.3em;
margin-bottom: 0.6em;
font-family: 'Alegreya Sans';
}
h2 {
font-weight: 800;
}
h3, h4, h2 time {
font-weight: 400;
}
@media (min-width: 1200px) {
.main > header, .main section > h2, .main section > h3, .main section > h4, .main section > p, .main section > blockquote, .main section > ul, .main section > table {
max-width: 80%;
}
}
code, button {
font-family: 'Roboto Mono';
font-weight: 400;
}
code, a > code {
background-color: #f8f3f0;
}
code {
color: #2f2625;
}
/*
* Chrome around code examples; see code.css for the styling of the code blocks themselves
*/
textarea {
position: absolute;
left: -99999px; /* Hide off canvas, while still remaining visible */
}
.code-example {
background-color: #2f2625;
padding: 1em;
border-radius: 0.3em;
margin-bottom: 1em;
}
.javascript-output-column {
border-left: 1px solid rgba(255, 255, 255, 0.2);
}
.btn-primary {
background-color: #69f0ae;
color: #0b140f;
border-color: #53d88f;
transition: 0.2s ease-in-out;
min-width: 3.125rem;
}
.btn-primary:active, .btn-primary:focus, .btn-primary:hover, .btn-primary:active:hover, .btn-primary:active:focus {
background-color: #61fea8;
color: #060a08;
border-color: #4de486;
outline: 0;
}
.play-button {
height: 1em;
width: 1em;
}
.javascript-output-column .CodeMirror-cursor {
/* https://github.com/codemirror/CodeMirror/issues/2568 */
display: none;
}
/*
* Try CoffeeScript
*/
.try-coffeescript {
position: fixed;
height: calc(100% - 3.5rem);
top: 3.5rem;
left: 0;
right: 0;
opacity: 0;
transition: opacity 0.15s ease-in-out;
z-index: -1001;
background-color: #2f2625;
}
.try-coffeescript.show {
opacity: 1;
z-index: 1001;
}
.try-coffeescript .CodeMirror {
height: calc(100vh - 7rem);
cursor: text;
}
.try-coffeescript .code-column {
overflow: hidden;
background-color: #2f2625;
color: #2f2625;
}
@media screen and (max-width: 767px) {
.try-coffeescript .code-column {
height: calc(50vh - 0.5 * 3.5rem);
}
}
@media screen and (min-width: 768px) {
.try-coffeescript .code-column {
padding-bottom: 100%;
margin-bottom: -100%;
}
}
.try-coffeescript button svg {
height: 1em;
transform: scale(1.3) translateY(0.1em);
fill: #0b140f;
}
@media screen and (max-width: 767px) {
.try-coffeescript .try-buttons {
position: absolute;
bottom: 1em;
z-index: 1002;
}
}
</style>
</head>
<body>
<nav class="navbar navbar-expand-lg fixed-top navbar-dark bg-dark bg-ribbed-dark site-navbar">
<a class="navbar-brand" href="#" data-close="try" data-action="scroll-to-top"><svg xmlns="http://www.w3.org/2000/svg" viewBox="-22 347 566 100">
<title>
CoffeeScript Logo
</title>
<path d="M21.7 351.1c.1.6-.2 1.1-1.2 1.6-1.3-.7-4.1-1.1-6.4-.9-2.5.2-4.6 1-4.3 2.7.4 1.7 2.8 2.7 7.1 2.3 10.5-.9 10.4-8 25.8-9.4 12-1.1 18.7 2.6 19.6 7.1.7 3.5-2.2 6.9-10.9 7.6-7.7.7-12.2-1.4-12.6-3.5-.2-1.1.4-2.7 4.1-3.1.4 1.7 2.5 3.5 7.5 3 3.6-.3 6.6-1.6 6.2-3.6-.4-2.1-4.2-3.3-10.2-2.8-12.2 1.1-15.2 7.8-25.6 8.7-7.4.7-13.4-2-14.2-6-.3-1.5-.3-5 7.5-5.7 4-.3 7.2.4 7.6 2zm-39 41.8c-3.4 4.3-4.9 9.3-4.6 14.2.3 4.9 2.7 8.9 6.5 12 4 3.1 8.3 4 13.2 3.1 1.9-.3 4-1.3 5.9-1.9-4 0-7.4-1.3-10.8-4-3.7-2.7-6.2-6.5-6.8-11.1-.9-4.3 0-8.3 2.4-11.8 2.7-3.4 6.2-5.3 10.8-5.9 4.6-.3 8.6.9 12.6 3.7-.9-1.3-2.2-2.2-3.4-3.4-4-2.7-8.3-4-13.6-2.7-4.8 1-8.8 3.5-12.2 7.8zm53.6-23.1c-12.9 0-24.4-1.3-32.7-3.1-8.9-2.2-13.6-4.6-13.6-7.7 0-1.3.6-2.4 2.4-3.7-5.6 2.2-8.6 4-8.6 6.8.3 3.1 5.3 6.2 15.5 8.6 9.6 2.4 21.9 3.7 36.7 3.7 15.1 0 27.1-1.3 36.7-3.7 10.2-2.4 15.1-5.6 15.1-8.6 0-2.2-2.2-4.3-6.2-5.9.9.6 1.6 1.6 1.6 2.7 0 3.1-4.6 5.6-13.9 7.7-8.6 1.9-19.6 3.2-33 3.2zm36.8 8.6c-9.6 2.2-21.9 3.7-36.7 3.7-15.1 0-27.4-1.6-37-3.7-8.6-2.2-13.2-4.6-14.8-7.1 1.6 10.8 5.3 21 10.2 30 3.7 5.6 7.4 10.5 11.1 15.8 1.6 3.1 2.7 6.2 3.4 9.3 2.4 3.4 5.9 5.6 10.2 6.8 5.3 1.9 10.8 2.7 16.4 2.4h.6c5.6.3 11.5-.6 16.9-2.4 4-1.3 7.4-3.4 9.9-6.8h.3c.6-3.1 1.6-6.2 3.1-9.3 3.7-5.3 7.4-10.2 11.1-15.8 4.9-8.9 8.3-19.1 10.2-30-2 2.8-6.6 5.2-14.9 7.1zm106.2 30.1c-4.8 12.1-17.6 16.9-25.9 16.9-13.4 0-19.9-6-19.9-22.3 0-16.5 7.9-47.3 31.7-47.3 8.5 0 15.2 3.3 15.2 12.1 0 4.8-1.8 8.3-6.4 8.3-1.5 0-3.4-.4-5.2-2.4 2.2-1.1 4.2-4.9 4.2-8.3 0-2.9-1.5-5.6-5.6-5.6-10 0-18.9 23.9-18.9 42.4 0 8.3 2.2 14.2 10.9 14.2 7.1 0 13.5-3.4 17.7-9.1l2.2 1.1zm32.9-16.3c.4.2.7.2 1 .2 4.2 0 10.1-2.7 14-5.5l.8 2.4c-3.4 3.7-9.5 6.5-16.1 7.5-1.5 16.8-10.6 27.3-21.7 27.3-8.4 0-14.5-4-14.5-14.4 0-10.5 6.2-32.2 24.9-32.2 7.8.3 11.6 5.3 11.6 14.7zm-7.7 5c-1.9-.5-2.4-2-2.4-3.8 0-2.5 1.2-4.2 2.8-4.9-.2-3.8-1.1-5.3-3.4-5.3-6.5 0-12 16.6-12 25.6 0 6 1.2 7.3 4.6 7.3 4.2.1 8.9-8 10.4-18.9zm-6.6 39.7c0-8.3 7.1-11 15.8-13.6l10.9-51.9c2.7-13 10.6-15.5 16.5-15.5 4.1 0 8 2.2 9.7 5.7 3.6-4.6 8.4-5.7 12.4-5.7 5.6 0 10.8 3.9 10.8 9.8 0 1.5-.1 2.6-.3 3.7h-4.3c.1-.9.2-1.7.2-2.4 0-2.1-1.7-3.1-3.4-3.1-2 0-4.8 1.1-6.2 7.1l-1.7 7.4h9.1l-.8 3.6h-9l-10.3 49.1c-2.7 13-10.6 15.5-16.5 15.5-5.2 0-8.3-2.3-9.8-5.7-3.5 4.6-8.3 5.7-12.3 5.7-5.6.1-10.8-3.8-10.8-9.7zm9.1 1.8c1.9 0 4.2-1.8 5.4-7.1l1.1-5.3c-5.7 2-10.1 4.4-10.1 9.4 0 1.2 1.7 3 3.6 3zm21.7 0c1.9 0 4.2-1.8 5.4-7.1l2.2-10.4-9.4 1.8-1.8 8.3c-.5 2.1-1.1 4-1.8 5.6.9 1.3 3 1.8 5.4 1.8zm-1.4-18l9.4-1.7 7.7-36.8h-9l-8.1 38.5zm16.6-56.7c-2 0-4.8 1.1-6.2 7.1l-1.7 7.4h9l2.1-9.5c.2-.7.2-1.3.2-2 .1-2-1.5-3-3.4-3zm37.9 53c7.1 0 11.6-4 16.1-9.2h3.1c-5.2 8.3-12.9 16.8-25 16.8-8.5 0-14.2-4.2-14.2-14.5 0-10.5 5.9-32.3 24.6-32.3 8.1 0 10 4.2 10 8.7 0 10.5-10 18.5-20.9 19.2-.1 1.3-.2 2.5-.2 3.6 0 6.2 2.2 7.7 6.5 7.7zm5.3-34.4c-4.6 0-9.1 9.7-10.9 18.7 7-.5 13.2-7.4 13.2-15 0-2.2-.5-3.7-2.3-3.7zm28.6 33.4c3.4 0 7.8-2.3 10.8-4.8-2 10.4-8.4 13.4-15.8 13.4-8.4 0-14.1-4.2-14.1-14.5 0-10.5 5.9-32.3 24.6-32.3 8.1 0 10 4.2 10 8.7 0 10.6-10 18.5-20.9 19.2-.1.9-.2 2-.2 2.7 0 5.7 2.5 7.6 5.6 7.6zm6.2-33.4c-4.5 0-9.1 10.1-11 18.7 7.1-.4 13.3-7.3 13.3-15 0-2.2-.6-3.7-2.3-3.7zm51.3-6.7c-1.7 0-3-.6-4.2-1.9 2.4-1.5 4.1-4.8 4.1-7.8 0-3.1-1.8-6.1-6.8-6.1s-8.3 2.8-8.3 8.2c0 13.3 20.5 15.2 20.5 34.8 0 15.3-12.3 22.7-25.6 22.7-10.4 0-19.3-4.5-19.3-15.7 0-9.8 7-14.9 13.3-14.9 3.1 0 7.7 1.3 8 6-4.9 0-10.7 2.3-10.7 8.5 0 4.5 2.9 8.7 8.7 8.7 6.1 0 10.6-4.4 10.6-12 0-15.6-18.6-21.1-18.6-34.5 0-9.5 9.3-16.3 21-16.3 4.3 0 14.6.9 14.6 10.9.1 5.5-2.8 9.4-7.3 9.4zm36.2 10.3c0-2.3-.8-3.7-2.5-3.7-5.7 0-11.7 16.6-11.7 26.7 0 6.2 2.2 7.6 6.6 7.6 7.1 0 11.6-4 16.1-9.2h3.1c-5.2 8.3-12.9 16.8-25 16.8-8.5 0-14.2-4.2-14.2-14.5 0-10.6 6-32.3 24.5-32.3 8.1 0 10.1 4.2 10.1 8.3 0 4.4-2.2 6.7-4.8 6.7-1 0-2.1-.4-3.1-1.1.5-1.9.9-3.6.9-5.3zm27.7-7.6l-1.2 5.7c3.1-2.7 6.7-5.7 11-5.7 4.1 0 6.3 3.3 6.3 6.9 0 3.1-2.1 6.7-6.6 6.7-5.1 0-2.5-6-5.3-6-2.7 0-4.4 1.4-6.7 3.4l-7.2 34.6h-13.1l9.6-45.4 13.2-.2zm34.2 0l-6.6 30.9c-.3 1.2-.4 2.1-.4 2.9 0 2.5 1.2 3.3 3.7 3.3 3.5 0 6.9-3.4 8.1-8h3.8c-5.2 14.8-14.2 16.8-19.1 16.8-5.5 0-9.7-3.2-9.7-10.9 0-1.8.3-3.7.7-5.9l6.2-29.2 13.3.1zm-4.1-19.4c4 0 7.2 3.2 7.2 7.2s-3.2 7.1-7.2 7.1-7.1-3.1-7.1-7.1c-.1-4 3.2-7.2 7.1-7.2zm29.1 16l-1.5 6.9c2.6-2.3 6.1-3.9 10.7-3.9 6.2 0 11.1 3.5 11.1 14.4 0 12.2-4.7 32.1-22.3 32.1-4.5 0-6.8-1.6-7.7-3.2l-4.7 22.1-13.7 3.2 15.2-71.5 12.9-.1zm7.8 17c0-7-2.9-7.5-4.5-7.5-2 0-4.5 1.6-6.3 4.4l-5.4 25.5c.4 1 1.4 2.1 3.4 2.1 9.7 0 12.8-15.9 12.8-24.5zm27.8 17.3c-.3 1.1-.5 2.2-.5 3.1 0 1.9.7 3.2 3.1 3.2.7 0 1.7 0 2.4-.3-2.5 7.8-6.6 8.9-9.6 8.9-6.4 0-9.1-4.4-9.1-10.3 0-1.6.2-3.1.6-4.8l5.8-27.2h-3l.7-3.6h3L528 366l13.4-1.9s-1.4 6.2-3.1 14.4h5.5l-.7 3.6h-5.5l-5.7 27.4z"></path>
</svg>
</a>
<button class="navbar-toggler" type="button" data-toggle="offcanvas" data-close="try" aria-label="Toggle sidebar">
<span class="navbar-toggler-icon"></span>
</button>
<nav class="collapse navbar-collapse">
<div class="navbar-nav mr-auto d-none d-lg-flex">
<a href="#try" id="try-link" class="nav-item nav-link" data-toggle="try">Try CoffeeScript</a>
<a href="#language" class="nav-item nav-link" data-close="try">Language Reference</a>
<a href="#resources" class="nav-item nav-link" data-close="try">Resources</a>
<a href="https://github.com/jashkenas/coffeescript/" class="nav-item nav-link" data-close="try">GitHub
</a>
</div>
</nav>
</nav>
<aside id="try" class="try-coffeescript container-fluid" data-example="try">
<div class="row">
<div class="col-md-6 code-column bg-ribbed-dark coffeescript-input-column">
<textarea class="coffeescript-input" id="try-coffeescript-coffee">alert 'Hello CoffeeScript!'</textarea>
</div>
<div class="col-md-6 code-column bg-ribbed-dark javascript-output-column">
<textarea class="javascript-output" id="try-coffeescript-js">alert('Hello CoffeeScript!');</textarea>
</div>
</div>
<div class="row">
<div class="col text-right try-buttons">
<button type="button" class="btn btn-primary" data-action="run-code-example" data-example="try-coffeescript" data-run="true"><svg class="play-button" viewBox="0 0 24 24">
<path d="M2.56-0.01v24.02L21.44 11.98 2.56-0.01z"></path>
</svg>
</button>&emsp;
</div>
</div>
</aside>
<div class="container-fluid" id="top">
<div class="row flex-nowrap main-row">
<nav class="sidebar bg-ribbed-light">
<nav id="contents" class="navbar contents">
<nav class="nav flex-column">
<a href="#try" class="nav-link d-md-none" data-action="sidebar-nav" data-toggle="try">Try CoffeeScript</a>
<a href="#introduction" class="nav-link" data-action="sidebar-nav">Introduction</a>
<a href="#overview" class="nav-link" data-action="sidebar-nav">Overview</a>
<a href="#coffeescript-2" class="nav-link" data-action="sidebar-nav">CoffeeScript 2</a>
<nav class="nav flex-column">
<a href="#whats-new-in-coffeescript-2" class="nav-link" data-action="sidebar-nav">Whats New in CoffeeScript 2</a>
<a href="#compatibility" class="nav-link" data-action="sidebar-nav">Compatibility</a>
</nav>
<a href="#installation" class="nav-link" data-action="sidebar-nav">Installation</a>
<a href="#usage" class="nav-link" data-action="sidebar-nav">Usage</a>
<nav class="nav flex-column">
<a href="#cli" class="nav-link" data-action="sidebar-nav">Command Line</a>
<a href="#nodejs-usage" class="nav-link" data-action="sidebar-nav">Node.js</a>
<a href="#transpilation" class="nav-link" data-action="sidebar-nav">Transpilation</a>
</nav>
<a href="#language" class="nav-link" data-action="sidebar-nav">Language Reference</a>
<nav class="nav flex-column">
<a href="#functions" class="nav-link" data-action="sidebar-nav">Functions</a>
<a href="#strings" class="nav-link" data-action="sidebar-nav">Strings</a>
<a href="#objects-and-arrays" class="nav-link" data-action="sidebar-nav">Objects and Arrays</a>
<a href="#comments" class="nav-link" data-action="sidebar-nav">Comments</a>
<a href="#lexical-scope" class="nav-link" data-action="sidebar-nav">Lexical Scoping and Variable Safety</a>
<a href="#conditionals" class="nav-link" data-action="sidebar-nav">If, Else, Unless, and Conditional Assignment</a>
<a href="#splats" class="nav-link" data-action="sidebar-nav">Splats, or Rest Parameters/Spread Syntax</a>
<a href="#loops" class="nav-link" data-action="sidebar-nav">Loops and Comprehensions</a>
<a href="#slices" class="nav-link" data-action="sidebar-nav">Array Slicing and Splicing</a>
<a href="#expressions" class="nav-link" data-action="sidebar-nav">Everything is an Expression</a>
<a href="#operators" class="nav-link" data-action="sidebar-nav">Operators and Aliases</a>
<a href="#existential-operator" class="nav-link" data-action="sidebar-nav">Existential Operator</a>
<a href="#destructuring" class="nav-link" data-action="sidebar-nav">Destructuring Assignment</a>
<a href="#chaining" class="nav-link" data-action="sidebar-nav">Chaining Function Calls</a>
<a href="#fat-arrow" class="nav-link" data-action="sidebar-nav">Bound (Fat Arrow) Functions</a>
<a href="#generators" class="nav-link" data-action="sidebar-nav">Generator Functions</a>
<a href="#async-functions" class="nav-link" data-action="sidebar-nav">Async Functions</a>
<a href="#classes" class="nav-link" data-action="sidebar-nav">Classes</a>
<a href="#prototypal-inheritance" class="nav-link" data-action="sidebar-nav">Prototypal Inheritance</a>
<a href="#switch" class="nav-link" data-action="sidebar-nav">Switch and Try/Catch</a>
<a href="#comparisons" class="nav-link" data-action="sidebar-nav">Chained Comparisons</a>
<a href="#regexes" class="nav-link" data-action="sidebar-nav">Block Regular Expressions</a>
<a href="#tagged-template-literals" class="nav-link" data-action="sidebar-nav">Tagged Template Literals</a>
<a href="#modules" class="nav-link" data-action="sidebar-nav">Modules</a>
<a href="#embedded" class="nav-link" data-action="sidebar-nav">Embedded JavaScript</a>
<a href="#jsx" class="nav-link" data-action="sidebar-nav">JSX</a>
</nav>
<a href="#type-annotations" class="nav-link" data-action="sidebar-nav">Type Annotations</a>
<a href="#literate" class="nav-link" data-action="sidebar-nav">Literate CoffeeScript</a>
<a href="#source-maps" class="nav-link" data-action="sidebar-nav">Source Maps</a>
<a href="#cake" class="nav-link" data-action="sidebar-nav">Cake, and Cakefiles</a>
<a href="#scripts" class="nav-link" data-action="sidebar-nav"><code>"text/coffeescript"</code> Script Tags</a>
<a href="test.html" class="nav-link" data-action="sidebar-nav">Browser-Based Tests</a>
<a href="#resources" class="nav-link" data-action="sidebar-nav">Resources</a>
<nav class="nav flex-column">
<a href="#books" class="nav-link" data-action="sidebar-nav">Books</a>
<a href="#screencasts" class="nav-link" data-action="sidebar-nav">Screencasts</a>
<a href="#examples" class="nav-link" data-action="sidebar-nav">Examples</a>
<a href="#chat" class="nav-link" data-action="sidebar-nav">Chat</a>
<a href="#annotated-source" class="nav-link" data-action="sidebar-nav">Annotated Source</a>
<a href="#contributing" class="nav-link" data-action="sidebar-nav">Contributing</a>
</nav>
<a href="https://github.com/jashkenas/coffeescript/" class="nav-item nav-link d-md-none" data-action="sidebar-nav">GitHub</a>
<a href="#unsupported" class="nav-link" data-action="sidebar-nav">Unsupported ECMAScript Features</a>
<nav class="nav flex-column">
<a href="#unsupported-let-const" class="nav-link" data-action="sidebar-nav"><code>let</code> and <code>const</code></a>
<a href="#unsupported-named-functions" class="nav-link" data-action="sidebar-nav">Named Functions and Function Declarations</a>
<a href="#unsupported-get-set" class="nav-link" data-action="sidebar-nav"><code>get</code> and <code>set</code> Shorthand Syntax</a>
</nav>
<a href="#breaking-changes" class="nav-link" data-action="sidebar-nav">Breaking Changes From 1.x</a>
<nav class="nav flex-column">
<a href="#breaking-changes-fat-arrow" class="nav-link" data-action="sidebar-nav">Bound (Fat Arrow) Functions</a>
<a href="#breaking-changes-default-values" class="nav-link" data-action="sidebar-nav">Default Values</a>
<a href="#breaking-changes-bound-generator-functions" class="nav-link" data-action="sidebar-nav">Bound Generator Functions</a>
<a href="#breaking-changes-classes" class="nav-link" data-action="sidebar-nav">Classes</a>
<a href="#breaking-changes-super-this" class="nav-link" data-action="sidebar-nav"><code>super</code> and <code>this</code></a>
<a href="#breaking-changes-super-extends" class="nav-link" data-action="sidebar-nav"><code>super</code> and <code>extends</code></a>
<a href="#breaking-changes-jsx-and-the-less-than-and-greater-than-operators" class="nav-link" data-action="sidebar-nav">JSX and the <code>&lt;</code> and <code>&gt;</code> Operators</a>
<a href="#breaking-changes-literate-coffeescript" class="nav-link" data-action="sidebar-nav">Literate CoffeeScript Parsing</a>
<a href="#breaking-changes-argument-parsing-and-shebang-lines" class="nav-link" data-action="sidebar-nav">Argument Parsing and <code>#!</code> Lines</a>
</nav>
<a href="#changelog" class="nav-link" data-action="sidebar-nav">Changelog</a>
<a href="/v1/" class="nav-link" data-action="sidebar-nav">Version 1.x Documentation</a>
</nav>
</nav>
</nav>
<main class="main">
<header class="d-none d-lg-block">
<p class="title-logo">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="-22 347 566 100">
<title>
CoffeeScript Logo
</title>
<path d="M21.7 351.1c.1.6-.2 1.1-1.2 1.6-1.3-.7-4.1-1.1-6.4-.9-2.5.2-4.6 1-4.3 2.7.4 1.7 2.8 2.7 7.1 2.3 10.5-.9 10.4-8 25.8-9.4 12-1.1 18.7 2.6 19.6 7.1.7 3.5-2.2 6.9-10.9 7.6-7.7.7-12.2-1.4-12.6-3.5-.2-1.1.4-2.7 4.1-3.1.4 1.7 2.5 3.5 7.5 3 3.6-.3 6.6-1.6 6.2-3.6-.4-2.1-4.2-3.3-10.2-2.8-12.2 1.1-15.2 7.8-25.6 8.7-7.4.7-13.4-2-14.2-6-.3-1.5-.3-5 7.5-5.7 4-.3 7.2.4 7.6 2zm-39 41.8c-3.4 4.3-4.9 9.3-4.6 14.2.3 4.9 2.7 8.9 6.5 12 4 3.1 8.3 4 13.2 3.1 1.9-.3 4-1.3 5.9-1.9-4 0-7.4-1.3-10.8-4-3.7-2.7-6.2-6.5-6.8-11.1-.9-4.3 0-8.3 2.4-11.8 2.7-3.4 6.2-5.3 10.8-5.9 4.6-.3 8.6.9 12.6 3.7-.9-1.3-2.2-2.2-3.4-3.4-4-2.7-8.3-4-13.6-2.7-4.8 1-8.8 3.5-12.2 7.8zm53.6-23.1c-12.9 0-24.4-1.3-32.7-3.1-8.9-2.2-13.6-4.6-13.6-7.7 0-1.3.6-2.4 2.4-3.7-5.6 2.2-8.6 4-8.6 6.8.3 3.1 5.3 6.2 15.5 8.6 9.6 2.4 21.9 3.7 36.7 3.7 15.1 0 27.1-1.3 36.7-3.7 10.2-2.4 15.1-5.6 15.1-8.6 0-2.2-2.2-4.3-6.2-5.9.9.6 1.6 1.6 1.6 2.7 0 3.1-4.6 5.6-13.9 7.7-8.6 1.9-19.6 3.2-33 3.2zm36.8 8.6c-9.6 2.2-21.9 3.7-36.7 3.7-15.1 0-27.4-1.6-37-3.7-8.6-2.2-13.2-4.6-14.8-7.1 1.6 10.8 5.3 21 10.2 30 3.7 5.6 7.4 10.5 11.1 15.8 1.6 3.1 2.7 6.2 3.4 9.3 2.4 3.4 5.9 5.6 10.2 6.8 5.3 1.9 10.8 2.7 16.4 2.4h.6c5.6.3 11.5-.6 16.9-2.4 4-1.3 7.4-3.4 9.9-6.8h.3c.6-3.1 1.6-6.2 3.1-9.3 3.7-5.3 7.4-10.2 11.1-15.8 4.9-8.9 8.3-19.1 10.2-30-2 2.8-6.6 5.2-14.9 7.1zm106.2 30.1c-4.8 12.1-17.6 16.9-25.9 16.9-13.4 0-19.9-6-19.9-22.3 0-16.5 7.9-47.3 31.7-47.3 8.5 0 15.2 3.3 15.2 12.1 0 4.8-1.8 8.3-6.4 8.3-1.5 0-3.4-.4-5.2-2.4 2.2-1.1 4.2-4.9 4.2-8.3 0-2.9-1.5-5.6-5.6-5.6-10 0-18.9 23.9-18.9 42.4 0 8.3 2.2 14.2 10.9 14.2 7.1 0 13.5-3.4 17.7-9.1l2.2 1.1zm32.9-16.3c.4.2.7.2 1 .2 4.2 0 10.1-2.7 14-5.5l.8 2.4c-3.4 3.7-9.5 6.5-16.1 7.5-1.5 16.8-10.6 27.3-21.7 27.3-8.4 0-14.5-4-14.5-14.4 0-10.5 6.2-32.2 24.9-32.2 7.8.3 11.6 5.3 11.6 14.7zm-7.7 5c-1.9-.5-2.4-2-2.4-3.8 0-2.5 1.2-4.2 2.8-4.9-.2-3.8-1.1-5.3-3.4-5.3-6.5 0-12 16.6-12 25.6 0 6 1.2 7.3 4.6 7.3 4.2.1 8.9-8 10.4-18.9zm-6.6 39.7c0-8.3 7.1-11 15.8-13.6l10.9-51.9c2.7-13 10.6-15.5 16.5-15.5 4.1 0 8 2.2 9.7 5.7 3.6-4.6 8.4-5.7 12.4-5.7 5.6 0 10.8 3.9 10.8 9.8 0 1.5-.1 2.6-.3 3.7h-4.3c.1-.9.2-1.7.2-2.4 0-2.1-1.7-3.1-3.4-3.1-2 0-4.8 1.1-6.2 7.1l-1.7 7.4h9.1l-.8 3.6h-9l-10.3 49.1c-2.7 13-10.6 15.5-16.5 15.5-5.2 0-8.3-2.3-9.8-5.7-3.5 4.6-8.3 5.7-12.3 5.7-5.6.1-10.8-3.8-10.8-9.7zm9.1 1.8c1.9 0 4.2-1.8 5.4-7.1l1.1-5.3c-5.7 2-10.1 4.4-10.1 9.4 0 1.2 1.7 3 3.6 3zm21.7 0c1.9 0 4.2-1.8 5.4-7.1l2.2-10.4-9.4 1.8-1.8 8.3c-.5 2.1-1.1 4-1.8 5.6.9 1.3 3 1.8 5.4 1.8zm-1.4-18l9.4-1.7 7.7-36.8h-9l-8.1 38.5zm16.6-56.7c-2 0-4.8 1.1-6.2 7.1l-1.7 7.4h9l2.1-9.5c.2-.7.2-1.3.2-2 .1-2-1.5-3-3.4-3zm37.9 53c7.1 0 11.6-4 16.1-9.2h3.1c-5.2 8.3-12.9 16.8-25 16.8-8.5 0-14.2-4.2-14.2-14.5 0-10.5 5.9-32.3 24.6-32.3 8.1 0 10 4.2 10 8.7 0 10.5-10 18.5-20.9 19.2-.1 1.3-.2 2.5-.2 3.6 0 6.2 2.2 7.7 6.5 7.7zm5.3-34.4c-4.6 0-9.1 9.7-10.9 18.7 7-.5 13.2-7.4 13.2-15 0-2.2-.5-3.7-2.3-3.7zm28.6 33.4c3.4 0 7.8-2.3 10.8-4.8-2 10.4-8.4 13.4-15.8 13.4-8.4 0-14.1-4.2-14.1-14.5 0-10.5 5.9-32.3 24.6-32.3 8.1 0 10 4.2 10 8.7 0 10.6-10 18.5-20.9 19.2-.1.9-.2 2-.2 2.7 0 5.7 2.5 7.6 5.6 7.6zm6.2-33.4c-4.5 0-9.1 10.1-11 18.7 7.1-.4 13.3-7.3 13.3-15 0-2.2-.6-3.7-2.3-3.7zm51.3-6.7c-1.7 0-3-.6-4.2-1.9 2.4-1.5 4.1-4.8 4.1-7.8 0-3.1-1.8-6.1-6.8-6.1s-8.3 2.8-8.3 8.2c0 13.3 20.5 15.2 20.5 34.8 0 15.3-12.3 22.7-25.6 22.7-10.4 0-19.3-4.5-19.3-15.7 0-9.8 7-14.9 13.3-14.9 3.1 0 7.7 1.3 8 6-4.9 0-10.7 2.3-10.7 8.5 0 4.5 2.9 8.7 8.7 8.7 6.1 0 10.6-4.4 10.6-12 0-15.6-18.6-21.1-18.6-34.5 0-9.5 9.3-16.3 21-16.3 4.3 0 14.6.9 14.6 10.9.1 5.5-2.8 9.4-7.3 9.4zm36.2 10.3c0-2.3-.8-3.7-2.5-3.7-5.7 0-11.7 16.6-11.7 26.7 0 6.2 2.2 7.6 6.6 7.6 7.1 0 11.6-4 16.1-9.2h3.1c-5.2 8.3-12.9 16.8-25 16.8-8.5 0-14.2-4.2-14.2-14.5 0-10.6 6-32.3 24.5-32.3 8.1 0 10.1 4.2 10.1 8.3 0 4.4-2.2 6.7-4.8 6.7-1 0-2.1-.4-3.1-1.1.5-1.9.9-3.6.9-5.3zm27.7-7.6l-1.2 5.7c3.1-2.7 6.7-5.7 11-5.7 4.1 0 6.3 3.3 6.3 6.9 0 3.1-2.1 6.7-6.6 6.7-5.1 0-2.5-6-5.3-6-2.7 0-4.4 1.4-6.7 3.4l-7.2 34.6h-13.1l9.6-45.4 13.2-.2zm34.2 0l-6.6 30.9c-.3 1.2-.4 2.1-.4 2.9 0 2.5 1.2 3.3 3.7 3.3 3.5 0 6.9-3.4 8.1-8h3.8c-5.2 14.8-14.2 16.8-19.1 16.8-5.5 0-9.7-3.2-9.7-10.9 0-1.8.3-3.7.7-5.9l6.2-29.2 13.3.1zm-4.1-19.4c4 0 7.2 3.2 7.2 7.2s-3.2 7.1-7.2 7.1-7.1-3.1-7.1-7.1c-.1-4 3.2-7.2 7.1-7.2zm29.1 16l-1.5 6.9c2.6-2.3 6.1-3.9 10.7-3.9 6.2 0 11.1 3.5 11.1 14.4 0 12.2-4.7 32.1-22.3 32.1-4.5 0-6.8-1.6-7.7-3.2l-4.7 22.1-13.7 3.2 15.2-71.5 12.9-.1zm7.8 17c0-7-2.9-7.5-4.5-7.5-2 0-4.5 1.6-6.3 4.4l-5.4 25.5c.4 1 1.4 2.1 3.4 2.1 9.7 0 12.8-15.9 12.8-24.5zm27.8 17.3c-.3 1.1-.5 2.2-.5 3.1 0 1.9.7 3.2 3.1 3.2.7 0 1.7 0 2.4-.3-2.5 7.8-6.6 8.9-9.6 8.9-6.4 0-9.1-4.4-9.1-10.3 0-1.6.2-3.1.6-4.8l5.8-27.2h-3l.7-3.6h3L528 366l13.4-1.9s-1.4 6.2-3.1 14.4h5.5l-.7 3.6h-5.5l-5.7 27.4z"></path>
</svg>
</p>
</header>
<section id="introduction">
<p><strong>CoffeeScript is a little language that compiles into JavaScript.</strong> Underneath that awkward Java-esque patina, JavaScript has always had a gorgeous heart. CoffeeScript is an attempt to expose the good parts of JavaScript in a simple way.</p>
<p>The golden rule of CoffeeScript is: <em>“Its just JavaScript.”</em> The code compiles one-to-one into the equivalent JS, and there is no interpretation at runtime. You can use any existing JavaScript library seamlessly from CoffeeScript (and vice-versa). The compiled output is readable, pretty-printed, and tends to run as fast or faster than the equivalent handwritten JavaScript.</p>
<p><strong>Latest Version:</strong> <a href="https://github.com/jashkenas/coffeescript/tarball/2.3.1">2.3.1</a></p>
<blockquote class="uneditable-code-block"><pre><code class="language-bash"><span class="comment"># Install locally for a project:</span>
npm install --save-dev coffeescript
<span class="comment"># Install globally to execute .coffee files anywhere:</span>
npm install --global coffeescript
</code></pre>
</blockquote>
</section>
<section id="overview">
<h2>Overview</h2>
<p><em>CoffeeScript on the <span class="d-md-none">top</span><span class="d-none d-md-inline">left</span>, compiled JavaScript output on the <span class="d-md-none">bottom</span><span class="d-none d-md-inline">right</span>. The CoffeeScript is editable!</em></p>
<aside class="code-example container-fluid bg-ribbed-dark" data-example="overview">
<div class="row">
<div class="col-md-6 coffeescript-input-column">
<textarea class="coffeescript-input" id="overview-coffee"># Assignment:
number = 42
opposite = true
# Conditions:
number = -42 if opposite
# Functions:
square = (x) -> x * x
# Arrays:
list = [1, 2, 3, 4, 5]
# Objects:
math =
root: Math.sqrt
square: square
cube: (x) -> x * square x
# Splats:
race = (winner, runners...) ->
print winner, runners
# Existence:
alert "I knew it!" if elvis?
# Array comprehensions:
cubes = (math.cube num for num in list)
</textarea>
<pre class="placeholder-code"><span class="cm-comment"># Assignment:</span>
<span class="cm-variable">number</span> <span class="cm-punctuation">=</span> <span class="cm-number">42</span>
<span class="cm-variable">opposite</span> <span class="cm-punctuation">=</span> <span class="cm-atom">true</span>
<span class="cm-comment"># Conditions:</span>
<span class="cm-variable">number</span> <span class="cm-punctuation">=</span> <span class="cm-number">-42</span> <span class="cm-keyword">if</span> <span class="cm-variable">opposite</span>
<span class="cm-comment"># Functions:</span>
<span class="cm-variable">square</span> <span class="cm-punctuation">=</span> <span class="cm-punctuation">(</span><span class="cm-variable">x</span><span class="cm-punctuation">)</span> <span class="cm-operator">-></span> <span class="cm-variable">x</span> <span class="cm-operator">*</span> <span class="cm-variable">x</span>
<span class="cm-comment"># Arrays:</span>
<span class="cm-variable">list</span> <span class="cm-punctuation">=</span> <span class="cm-punctuation">[</span><span class="cm-number">1</span><span class="cm-punctuation">,</span> <span class="cm-number">2</span><span class="cm-punctuation">,</span> <span class="cm-number">3</span><span class="cm-punctuation">,</span> <span class="cm-number">4</span><span class="cm-punctuation">,</span> <span class="cm-number">5</span><span class="cm-punctuation">]</span>
<span class="cm-comment"># Objects:</span>
<span class="cm-variable">math</span> <span class="cm-punctuation">=</span>
<span class="cm-indent"> </span><span class="cm-variable">root</span><span class="cm-punctuation">:</span> <span class="cm-variable">Math</span><span class="cm-punctuation">.</span><span class="cm-property">sqrt</span>
<span class="cm-variable">square</span><span class="cm-punctuation">:</span> <span class="cm-variable">square</span>
<span class="cm-variable">cube</span><span class="cm-punctuation">:</span> <span class="cm-punctuation">(</span><span class="cm-variable">x</span><span class="cm-punctuation">)</span> <span class="cm-operator">-></span> <span class="cm-variable">x</span> <span class="cm-operator">*</span> <span class="cm-variable">square</span> <span class="cm-variable">x</span>
<span class="cm-comment"># Splats:</span>
<span class="cm-variable">race</span> <span class="cm-punctuation">=</span> <span class="cm-punctuation">(</span><span class="cm-variable">winner</span><span class="cm-punctuation">,</span> <span class="cm-variable">runners</span><span class="cm-punctuation">...)</span> <span class="cm-operator">-></span>
<span class="cm-variable">print</span> <span class="cm-variable">winner</span><span class="cm-punctuation">,</span> <span class="cm-variable">runners</span>
<span class="cm-comment"># Existence:</span>
<span class="cm-variable">alert</span> <span class="cm-string">"I knew it!"</span> <span class="cm-keyword">if</span> <span class="cm-variable">elvis</span><span class="cm-operator">?</span>
<span class="cm-comment"># Array comprehensions:</span>
<span class="cm-variable">cubes</span> <span class="cm-punctuation">=</span> <span class="cm-punctuation">(</span><span class="cm-variable">math</span><span class="cm-punctuation">.</span><span class="cm-property">cube</span> <span class="cm-variable">num</span> <span class="cm-keyword">for</span> <span class="cm-variable">num</span> <span class="cm-operator">in</span> <span class="cm-variable">list</span><span class="cm-punctuation">)</span>
</pre>
</div>
<div class="col-md-6 javascript-output-column">
<textarea class="javascript-output" id="overview-js">// Assignment:
var cubes, list, math, num, number, opposite, race, square;
number = 42;
opposite = true;
if (opposite) {
// Conditions:
number = -42;
}
// Functions:
square = function(x) {
return x * x;
};
// Arrays:
list = [1, 2, 3, 4, 5];
// Objects:
math = {
root: Math.sqrt,
square: square,
cube: function(x) {
return x * square(x);
}
};
// Splats:
race = function(winner, ...runners) {
return print(winner, runners);
};
if (typeof elvis !== "undefined" && elvis !== null) {
// Existence:
alert("I knew it!");
}
// Array comprehensions:
cubes = (function() {
var i, len, results;
results = [];
for (i = 0, len = list.length; i < len; i++) {
num = list[i];
results.push(math.cube(num));
}
return results;
})();
</textarea>
<pre class="placeholder-code"><span class="cm-comment">// Assignment:</span>
<span class="cm-keyword">var</span> <span class="cm-def">cubes</span>, <span class="cm-def">list</span>, <span class="cm-def">math</span>, <span class="cm-def">num</span>, <span class="cm-def">number</span>, <span class="cm-def">opposite</span>, <span class="cm-def">race</span>, <span class="cm-def">square</span>;
<span class="cm-variable">number</span> <span class="cm-operator">=</span> <span class="cm-number">42</span>;
<span class="cm-variable">opposite</span> <span class="cm-operator">=</span> <span class="cm-atom">true</span>;
<span class="cm-keyword">if</span> (<span class="cm-variable">opposite</span>) {
<span class="cm-comment">// Conditions:</span>
<span class="cm-variable">number</span> <span class="cm-operator">=</span> <span class="cm-operator">-</span><span class="cm-number">42</span>;
}
<span class="cm-comment">// Functions:</span>
<span class="cm-variable">square</span> <span class="cm-operator">=</span> <span class="cm-keyword">function</span>(<span class="cm-def">x</span>) {
<span class="cm-keyword">return</span> <span class="cm-variable-2">x</span> <span class="cm-operator">*</span> <span class="cm-variable-2">x</span>;
};
<span class="cm-comment">// Arrays:</span>
<span class="cm-variable">list</span> <span class="cm-operator">=</span> [<span class="cm-number">1</span>, <span class="cm-number">2</span>, <span class="cm-number">3</span>, <span class="cm-number">4</span>, <span class="cm-number">5</span>];
<span class="cm-comment">// Objects:</span>
<span class="cm-variable">math</span> <span class="cm-operator">=</span> {
<span class="cm-property">root</span>: <span class="cm-variable">Math</span>.<span class="cm-property">sqrt</span>,
<span class="cm-property">square</span>: <span class="cm-variable">square</span>,
<span class="cm-property">cube</span>: <span class="cm-keyword">function</span>(<span class="cm-def">x</span>) {
<span class="cm-keyword">return</span> <span class="cm-variable-2">x</span> <span class="cm-operator">*</span> <span class="cm-variable">square</span>(<span class="cm-variable-2">x</span>);
}
};
<span class="cm-comment">// Splats:</span>
<span class="cm-variable">race</span> <span class="cm-operator">=</span> <span class="cm-keyword">function</span>(<span class="cm-def">winner</span>, <span class="cm-meta">...</span><span class="cm-def">runners</span>) {
<span class="cm-keyword">return</span> <span class="cm-variable">print</span>(<span class="cm-variable-2">winner</span>, <span class="cm-variable-2">runners</span>);
};
<span class="cm-keyword">if</span> (<span class="cm-keyword">typeof</span> <span class="cm-variable">elvis</span> <span class="cm-operator">!==</span> <span class="cm-string">"undefined"</span> <span class="cm-operator">&amp;&amp;</span> <span class="cm-variable">elvis</span> <span class="cm-operator">!==</span> <span class="cm-atom">null</span>) {
<span class="cm-comment">// Existence:</span>
<span class="cm-variable">alert</span>(<span class="cm-string">"I knew it!"</span>);
}
<span class="cm-comment">// Array comprehensions:</span>
<span class="cm-variable">cubes</span> <span class="cm-operator">=</span> (<span class="cm-keyword">function</span>() {
<span class="cm-keyword">var</span> <span class="cm-def">i</span>, <span class="cm-def">len</span>, <span class="cm-def">results</span>;
<span class="cm-variable-2">results</span> <span class="cm-operator">=</span> [];
<span class="cm-keyword">for</span> (<span class="cm-variable-2">i</span> <span class="cm-operator">=</span> <span class="cm-number">0</span>, <span class="cm-variable-2">len</span> <span class="cm-operator">=</span> <span class="cm-variable">list</span>.<span class="cm-property">length</span>; <span class="cm-variable-2">i</span> <span class="cm-operator">&lt;</span> <span class="cm-variable-2">len</span>; <span class="cm-variable-2">i</span><span class="cm-operator">++</span>) {
<span class="cm-variable">num</span> <span class="cm-operator">=</span> <span class="cm-variable">list</span>[<span class="cm-variable-2">i</span>];
<span class="cm-variable-2">results</span>.<span class="cm-property">push</span>(<span class="cm-variable">math</span>.<span class="cm-property">cube</span>(<span class="cm-variable">num</span>));
}
<span class="cm-keyword">return</span> <span class="cm-variable-2">results</span>;
})();
</pre>
</div>
</div>
<div class="row">
<div class="col text-right">
<button type="button" class="btn btn-primary" data-action="run-code-example" data-example="overview" data-run="cubes"><small><svg class="play-button" viewBox="0 0 24 24">
<path d="M2.56-0.01v24.02L21.44 11.98 2.56-0.01z"></path>
</svg>
</small>cubes</button>
</div>
</div>
</aside>
</section>
<section id="coffeescript-2">
<h2>CoffeeScript 2</h2>
<section id="whats-new-in-coffeescript-2">
<h3>Whats New In CoffeeScript 2?</h3>
<p>The biggest change in CoffeeScript 2 is that now the CoffeeScript compiler produces modern JavaScript syntax (ES6, or ES2015 and later). A CoffeeScript <code>=&gt;</code> becomes a JS <code>=&gt;</code>, a CoffeeScript <code>class</code> becomes a JS <code>class</code> and so on. Major new features in CoffeeScript 2 include <a href="#async-functions">async functions</a> and <a href="#jsx">JSX</a>. You can read more in the <a href="announcing-coffeescript-2/">announcement</a>.</p>
<p>There are very few <a href="#breaking-changes">breaking changes from CoffeeScript 1.x to 2</a>; we hope the upgrade process is smooth for most projects.</p>
</section>
<section id="compatibility">
<h3>Compatibility</h3>
<p>Most modern JavaScript features that CoffeeScript supports can run natively in Node 7.6+, meaning that Node can run CoffeeScripts output without any further processing required. Here are some notable exceptions:</p>
<ul>
<li><a href="#modules">Modules</a> and <a href="#jsx">JSX</a> always require transpilation.</li>
<li><a href="https://coffeescript.org/#splats">Splats, a.k.a. object rest/spread syntax, for objects</a> are supported by Node 8.6+.</li>
<li>The <a href="https://github.com/tc39/proposal-regexp-dotall-flag">regular expression <code>s</code> (dotall) flag</a> is supported by Node 9+.</li>
<li><a href="https://github.com/tc39/proposal-async-iteration">Async generator functions</a> are supported by Node 10+.</li>
</ul>
<p>This list may be incomplete, and excludes versions of Node that support newer features behind flags; please refer to <a href="http://node.green/">node.green</a> for full details. You can <a href="test.html">run the tests in your browser</a> to see what your browser supports. It is your responsibility to ensure that your runtime supports the modern features you use; or that you <a href="#transpilation">transpile</a> your code. When in doubt, transpile.</p>
</section>
</section>
<section id="installation">
<h2>Installation</h2>
<p>The command-line version of <code>coffee</code> is available as a <a href="https://nodejs.org/">Node.js</a> utility, requiring Node 6 or later. The <a href="/v2/browser-compiler/coffeescript.js">core compiler</a> however, does not depend on Node, and can be run in any JavaScript environment, or in the browser (see <a href="#try">Try CoffeeScript</a>).</p>
<p>To install, first make sure you have a working copy of the latest stable version of <a href="https://nodejs.org/">Node.js</a>. You can then install CoffeeScript globally with <a href="https://www.npmjs.com/">npm</a>:</p>
<blockquote class="uneditable-code-block"><pre><code class="language-bash">npm install --global coffeescript
</code></pre>
</blockquote><p>This will make the <code>coffee</code> and <code>cake</code> commands available globally.</p>
<p>If you are using CoffeeScript in a project, you should install it locally for that project so that the version of CoffeeScript is tracked as one of your projects dependencies. Within that projects folder:</p>
<blockquote class="uneditable-code-block"><pre><code class="language-bash">npm install --save-dev coffeescript
</code></pre>
</blockquote><p>The <code>coffee</code> and <code>cake</code> commands will first look in the current folder to see if CoffeeScript is installed locally, and use that version if so. This allows different versions of CoffeeScript to be installed globally and locally.</p>
<p>If you plan to use the <code>--transpile</code> option (see <a href="#transpilation">Transpilation</a>) you will need to also install <code>@babel/core</code> either globally or locally, depending on whether you are running a globally or locally installed version of CoffeeScript.</p>
</section>
<section id="usage">
<h2>Usage</h2>
<section id="cli">
<h3>Command Line</h3>
<p>Once installed, you should have access to the <code>coffee</code> command, which can execute scripts, compile <code>.coffee</code> files into <code>.js</code>, and provide an interactive REPL. The <code>coffee</code> command takes the following options:</p>
<table>
<thead>
<tr>
<th>Option</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>-c, --compile</code></td>
<td>Compile a <code>.coffee</code> script into a <code>.js</code> JavaScript file of the same name.</td>
</tr>
<tr>
<td><code>-t, --transpile</code></td>
<td>Pipe the CoffeeScript compilers output through Babel before saving or running the generated JavaScript. Requires <code>@babel/core</code> to be installed, and options to pass to Babel in a <code>.babelrc</code> file or a <code>package.json</code> with a <code>babel</code> key in the path of the file or folder to be compiled. See <a href="#transpilation">Transpilation</a>.</td>
</tr>
<tr>
<td><code>-m, --map</code></td>
<td>Generate source maps alongside the compiled JavaScript files. Adds <code>sourceMappingURL</code> directives to the JavaScript as well.</td>
</tr>
<tr>
<td><code>-M, --inline-map</code></td>
<td>Just like <code>--map</code>, but include the source map directly in the compiled JavaScript files, rather than in a separate file.</td>
</tr>
<tr>
<td><code>-i, --interactive</code></td>
<td>Launch an interactive CoffeeScript session to try short snippets. Identical to calling <code>coffee</code> with no arguments.</td>
</tr>
<tr>
<td><code>-o, --output [DIR]</code></td>
<td>Write out all compiled JavaScript files into the specified directory. Use in conjunction with <code>--compile</code> or <code>--watch</code>.</td>
</tr>
<tr>
<td><code>-w, --watch</code></td>
<td>Watch files for changes, rerunning the specified command when any file is updated.</td>
</tr>
<tr>
<td><code>-p, --print</code></td>
<td>Instead of writing out the JavaScript as a file, print it directly to <strong>stdout</strong>.</td>
</tr>
<tr>
<td><code>-s, --stdio</code></td>
<td>Pipe in CoffeeScript to STDIN and get back JavaScript over STDOUT. Good for use with processes written in other languages. An example:<br><code>cat src/cake.coffee | coffee -sc</code></td>
</tr>
<tr>
<td><code>-l, --literate</code></td>
<td>Parses the code as Literate CoffeeScript. You only need to specify this when passing in code directly over <strong>stdio</strong>, or using some sort of extension-less file name.</td>
</tr>
<tr>
<td><code>-e, --eval</code></td>
<td>Compile and print a little snippet of CoffeeScript directly from the command line. For example:<br><code>coffee -e &quot;console.log num for num in [10..1]&quot;</code></td>
</tr>
<tr>
<td><code>-r, --require [MODULE]</code></td>
<td><code>require()</code> the given module before starting the REPL or evaluating the code given with the <code>--eval</code> flag.</td>
</tr>
<tr>
<td><code>-b, --bare</code></td>
<td>Compile the JavaScript without the <a href="#lexical-scope">top-level function safety wrapper</a>.</td>
</tr>
<tr>
<td><code>--no-header</code></td>
<td>Suppress the “Generated by CoffeeScript” header.</td>
</tr>
<tr>
<td><code>--nodejs</code></td>
<td>The <code>node</code> executable has some useful options you can set, such as <code>--debug</code>, <code>--debug-brk</code>, <code>--max-stack-size</code>, and <code>--expose-gc</code>. Use this flag to forward options directly to Node.js. To pass multiple flags, use <code>--nodejs</code> multiple times.</td>
</tr>
<tr>
<td><code>--tokens</code></td>
<td>Instead of parsing the CoffeeScript, just lex it, and print out the token stream. Used for debugging the compiler.</td>
</tr>
<tr>
<td><code>-n, --nodes</code></td>
<td>Instead of compiling the CoffeeScript, just lex and parse it, and print out the parse tree. Used for debugging the compiler.</td>
</tr>
</tbody>
</table>
<h4>Examples:</h4>
<ul>
<li>Compile a directory tree of <code>.coffee</code> files in <code>src</code> into a parallel tree of <code>.js</code> files in <code>lib</code>:<br>
<code>coffee --compile --output lib/ src/</code></li>
<li>Watch a file for changes, and recompile it every time the file is saved:<br>
<code>coffee --watch --compile experimental.coffee</code></li>
<li>Concatenate a list of files into a single script:<br>
<code>coffee --join project.js --compile src/*.coffee</code></li>
<li>Print out the compiled JS from a one-liner:<br>
<code>coffee -bpe &quot;alert i for i in [0..10]&quot;</code></li>
<li>All together now, watch and recompile an entire project as you work on it:<br>
<code>coffee -o lib/ -cw src/</code></li>
<li>Start the CoffeeScript REPL (<code>Ctrl-D</code> to exit, <code>Ctrl-V</code>for multi-line):<br>
<code>coffee</code></li>
</ul>
<p>To use <code>--transpile</code>, see <a href="#transpilation">Transpilation</a>.</p>
</section>
<section id="nodejs-usage">
<h3>Node.js</h3>
<p>If youd like to use Node.js CommonJS to <code>require</code> CoffeeScript files, e.g. <code>require './app.coffee'</code>, you must first “register” CoffeeScript as an extension:</p>
<blockquote class="uneditable-code-block"><pre><code class="language-coffee"><span class="built_in">require</span> <span class="string">'coffeescript/register'</span>
App = <span class="built_in">require</span> <span class="string">'./app'</span> <span class="comment"># The .coffee extension is optional</span>
</code></pre>
</blockquote><p>If you want to use the compilers API, for example to make an app that compiles strings of CoffeeScript on the fly, you can <code>require</code> the full module:</p>
<blockquote class="uneditable-code-block"><pre><code class="language-coffee">CoffeeScript = <span class="built_in">require</span> <span class="string">'coffeescript'</span>
eval CoffeeScript.compile <span class="string">'console.log "Mmmmm, I could really go for some #{Math.pi}"'</span>
</code></pre>
</blockquote><p>The <code>compile</code> method has the signature <code>compile(code, options)</code> where <code>code</code> is a string of CoffeeScript code, and the optional <code>options</code> is an object with some or all of the following properties:</p>
<ul>
<li><code>options.sourceMap</code>, boolean: if true, a source map will be generated; and instead of returning a string, <code>compile</code> will return an object of the form <code>{js, v3SourceMap, sourceMap}</code>.</li>
<li><code>options.inlineMap</code>, boolean: if true, output the source map as a base64-encoded string in a comment at the bottom.</li>
<li><code>options.filename</code>, string: the filename to use for the source map. It can include a path (relative or absolute).</li>
<li><code>options.bare</code>, boolean: if true, output without the <a href="#lexical-scope">top-level function safety wrapper</a>.</li>
<li><code>options.header</code>, boolean: if true, output the <code>Generated by CoffeeScript</code> header.</li>
<li><code>options.transpile</code>, <strong>object</strong>: if set, this must be an object with the <a href="http://babeljs.io/docs/usage/api/#options">options to pass to Babel</a>. See <a href="#transpilation">Transpilation</a>.</li>
</ul>
</section>
<section id="transpilation">
<h3>Transpilation</h3>
<p>CoffeeScript 2 generates JavaScript that uses the latest, modern syntax. The runtime or browsers where you want your code to run <a href="#compatibility">might not support all of that syntax</a>. In that case, we want to convert modern JavaScript into older JavaScript that will run in older versions of Node or older browsers; for example, <code>{ a } = obj</code> into <code>a = obj.a</code>. This is done via transpilers like <a href="http://babeljs.io/">Babel</a>, <a href="https://buble.surge.sh/">Bublé</a> or <a href="https://github.com/google/traceur-compiler">Traceur Compiler</a>.</p>
<h4>Quickstart</h4>
<p>From the root of your project:</p>
<blockquote class="uneditable-code-block"><pre><code class="language-bash">npm install --save-dev @babel/core @babel/preset-env
<span class="built_in">echo</span> <span class="string">'{ "presets": ["@babel/env"] }'</span> &gt; .babelrc
coffee --compile --transpile --inline-map some-file.coffee
</code></pre>
</blockquote><h4>Transpiling with the CoffeeScript compiler</h4>
<p>To make things easy, CoffeeScript has built-in support for the popular <a href="http://babeljs.io/">Babel</a> transpiler. You can use it via the <code>--transpile</code> command-line option or the <code>transpile</code> Node API option. To use either, <code>@babel/core</code> must be installed in your project:</p>
<blockquote class="uneditable-code-block"><pre><code class="language-bash">npm install --save-dev @babel/core
</code></pre>
</blockquote><p>Or if youre running the <code>coffee</code> command outside of a project folder, using a globally-installed <code>coffeescript</code> module, <code>@babel/core</code> needs to be installed globally:</p>
<blockquote class="uneditable-code-block"><pre><code class="language-bash">npm install --global @babel/core
</code></pre>
</blockquote><p>By default, Babel doesnt do anything—it doesnt make assumptions about what you want to transpile to. You need to provide it with a configuration so that it knows what to do. One way to do this is by creating a <a href="https://babeljs.io/docs/usage/babelrc/"><code>.babelrc</code> file</a> in the folder containing the files youre compiling, or in any parent folder up the path above those files. (Babel supports <a href="https://babeljs.io/docs/usage/babelrc/">other ways</a>, too.) A minimal <code>.babelrc</code> file would be just <code>{ &quot;presets&quot;: [&quot;@babel/env&quot;] }</code>. This implies that you have installed <a href="https://babeljs.io/docs/plugins/preset-env/"><code>@babel/preset-env</code></a>:</p>
<blockquote class="uneditable-code-block"><pre><code class="language-bash">npm install --save-dev @babel/preset-env <span class="comment"># Or --global for non-project-based usage</span>
</code></pre>
</blockquote><p>See <a href="https://babeljs.io/docs/plugins/">Babels website to learn about presets and plugins</a> and the multitude of options you have. Another preset you might need is <a href="https://babeljs.io/docs/en/babel-plugin-transform-react-jsx/"><code>@babel/plugin-transform-react-jsx</code></a> if youre using JSX with React (JSX can also be used with other frameworks).</p>
<p>Once you have <code>@babel/core</code> and <code>@babel/preset-env</code> (or other presets or plugins) installed, and a <code>.babelrc</code> file (or other equivalent) in place, you can use <code>coffee --transpile</code> to pipe CoffeeScripts output through Babel using the options youve saved.</p>
<p>If youre using CoffeeScript via the <a href="nodejs_usage">Node API</a>, where you call <code>CoffeeScript.compile</code> with a string to be compiled and an <code>options</code> object, the <code>transpile</code> key of the <code>options</code> object should be the Babel options:</p>
<blockquote class="uneditable-code-block"><pre><code class="language-js">CoffeeScript.compile(code, {<span class="attr">transpile</span>: {<span class="attr">presets</span>: [<span class="string">'@babel/env'</span>]}})
</code></pre>
</blockquote><p>You can also transpile CoffeeScripts output without using the <code>transpile</code> option, for example as part of a build chain. This lets you use transpilers other than Babel, and it gives you greater control over the process. There are many great task runners for setting up JavaScript build chains, such as <a href="http://gulpjs.com/">Gulp</a>, <a href="https://webpack.github.io/">Webpack</a>, <a href="https://gruntjs.com/">Grunt</a> and <a href="http://broccolijs.com/">Broccoli</a>.</p>
<h4>Polyfills</h4>
<p>Note that transpiling doesnt automatically supply <a href="https://developer.mozilla.org/en-US/docs/Glossary/Polyfill">polyfills</a> for your code. CoffeeScript itself will output <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf"><code>Array.indexOf</code></a> if you use the <code>in</code> operator, or destructuring or spread/rest syntax; and <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind"><code>Function.bind</code></a> if you use a bound (<code>=&gt;</code>) method in a class. Both are supported in Internet Explorer 9+ and all more recent browsers, but you will need to supply polyfills if you need to support Internet Explorer 8 or below and are using features that would cause these methods to be output. Youll also need to supply polyfills if your own code uses these methods or another method added in recent versions of JavaScript. One polyfill option is <a href="https://babeljs.io/docs/en/babel-polyfill/"><code>@babel/polyfill</code></a>, though there are many <a href="https://hackernoon.com/polyfills-everything-you-ever-wanted-to-know-or-maybe-a-bit-less-7c8de164e423">other</a> <a href="https://philipwalton.com/articles/loading-polyfills-only-when-needed/">strategies</a>.</p>
</section>
</section>
<section id="language">
<h2>Language Reference</h2>
<p><em>This reference is structured so that it can be read from top to bottom, if you like. Later sections use ideas and syntax previously introduced. Familiarity with JavaScript is assumed. In all of the following examples, the source CoffeeScript is provided on the left, and the direct compilation into JavaScript is on the right.</em></p>
<p><em>Many of the examples can be run (where it makes sense) by pressing the</em> <small></small> <em>button on the right. The CoffeeScript on the left is editable, and the JavaScript will update as you edit.</em></p>
<p>First, the basics: CoffeeScript uses significant whitespace to delimit blocks of code. You dont need to use semicolons <code>;</code> to terminate expressions, ending the line will do just as well (although semicolons can still be used to fit multiple expressions onto a single line). Instead of using curly braces <code>{ }</code> to surround blocks of code in <a href="#literals">functions</a>, <a href="#conditionals">if-statements</a>, <a href="#switch">switch</a>, and <a href="#try">try/catch</a>, use indentation.</p>
<p>You dont need to use parentheses to invoke a function if youre passing arguments. The implicit call wraps forward to the end of the line or block expression.<br>
<code>console.log sys.inspect object</code><code>console.log(sys.inspect(object));</code></p>
<section id="functions">
<h2>Functions</h2>
<p>Functions are defined by an optional list of parameters in parentheses, an arrow, and the function body. The empty function looks like this: <code>-&gt;</code></p>
<aside class="code-example container-fluid bg-ribbed-dark" data-example="functions">
<div class="row">
<div class="col-md-6 coffeescript-input-column">
<textarea class="coffeescript-input" id="functions-coffee">square = (x) -> x * x
cube = (x) -> square(x) * x
</textarea>
<pre class="placeholder-code"><span class="cm-variable">square</span> <span class="cm-punctuation">=</span> <span class="cm-punctuation">(</span><span class="cm-variable">x</span><span class="cm-punctuation">)</span> <span class="cm-operator">-></span> <span class="cm-variable">x</span> <span class="cm-operator">*</span> <span class="cm-variable">x</span>
<span class="cm-variable">cube</span> <span class="cm-punctuation">=</span> <span class="cm-punctuation">(</span><span class="cm-variable">x</span><span class="cm-punctuation">)</span> <span class="cm-operator">-></span> <span class="cm-variable">square</span><span class="cm-punctuation">(</span><span class="cm-variable">x</span><span class="cm-punctuation">)</span> <span class="cm-operator">*</span> <span class="cm-variable">x</span>
</pre>
</div>
<div class="col-md-6 javascript-output-column">
<textarea class="javascript-output" id="functions-js">var cube, square;
square = function(x) {
return x * x;
};
cube = function(x) {
return square(x) * x;
};
</textarea>
<pre class="placeholder-code"><span class="cm-keyword">var</span> <span class="cm-def">cube</span>, <span class="cm-def">square</span>;
<span class="cm-variable">square</span> <span class="cm-operator">=</span> <span class="cm-keyword">function</span>(<span class="cm-def">x</span>) {
<span class="cm-keyword">return</span> <span class="cm-variable-2">x</span> <span class="cm-operator">*</span> <span class="cm-variable-2">x</span>;
};
<span class="cm-variable">cube</span> <span class="cm-operator">=</span> <span class="cm-keyword">function</span>(<span class="cm-def">x</span>) {
<span class="cm-keyword">return</span> <span class="cm-variable">square</span>(<span class="cm-variable-2">x</span>) <span class="cm-operator">*</span> <span class="cm-variable-2">x</span>;
};
</pre>
</div>
</div>
<div class="row">
<div class="col text-right">
<button type="button" class="btn btn-primary" data-action="run-code-example" data-example="functions" data-run="cube%285%29"><small><svg class="play-button" viewBox="0 0 24 24">
<path d="M2.56-0.01v24.02L21.44 11.98 2.56-0.01z"></path>
</svg>
</small>cube(5)</button>
</div>
</div>
</aside>
<p>Functions may also have default values for arguments, which will be used if the incoming argument is missing (<code>undefined</code>).</p>
<aside class="code-example container-fluid bg-ribbed-dark" data-example="default_args">
<div class="row">
<div class="col-md-6 coffeescript-input-column">
<textarea class="coffeescript-input" id="default_args-coffee">fill = (container, liquid = "coffee") ->
"Filling the #{container} with #{liquid}..."
</textarea>
<pre class="placeholder-code"><span class="cm-variable">fill</span> <span class="cm-punctuation">=</span> <span class="cm-punctuation">(</span><span class="cm-variable">container</span><span class="cm-punctuation">,</span> <span class="cm-variable">liquid</span> <span class="cm-punctuation">=</span> <span class="cm-string">"coffee"</span><span class="cm-punctuation">)</span> <span class="cm-operator">-></span>
<span class="cm-string">"Filling the #{container} with #{liquid}..."</span>
</pre>
</div>
<div class="col-md-6 javascript-output-column">
<textarea class="javascript-output" id="default_args-js">var fill;
fill = function(container, liquid = "coffee") {
return `Filling the ${container} with ${liquid}...`;
};
</textarea>
<pre class="placeholder-code"><span class="cm-keyword">var</span> <span class="cm-def">fill</span>;
<span class="cm-variable">fill</span> <span class="cm-operator">=</span> <span class="cm-keyword">function</span>(<span class="cm-def">container</span>, <span class="cm-def">liquid</span> <span class="cm-operator">=</span> <span class="cm-string">"coffee"</span>) {
<span class="cm-keyword">return</span> <span class="cm-string-2">`Filling the ${</span><span class="cm-variable-2">container</span><span class="cm-string-2">}</span> <span class="cm-string-2">with ${</span><span class="cm-variable-2">liquid</span><span class="cm-string-2">}...`</span>;
};
</pre>
</div>
</div>
<div class="row">
<div class="col text-right">
<button type="button" class="btn btn-primary" data-action="run-code-example" data-example="default_args" data-run="fill%28%22cup%22%29"><small><svg class="play-button" viewBox="0 0 24 24">
<path d="M2.56-0.01v24.02L21.44 11.98 2.56-0.01z"></path>
</svg>
</small>fill(&quot;cup&quot;)</button>
</div>
</div>
</aside>
</section>
<section id="strings">
<h2>Strings</h2>
<p>Like JavaScript and many other languages, CoffeeScript supports strings as delimited by the <code>&quot;</code> or <code>'</code> characters. CoffeeScript also supports string interpolation within <code>&quot;</code>-quoted strings, using <code>#{ … }</code>. Single-quoted strings are literal. You may even use interpolation in object keys.</p>
<aside class="code-example container-fluid bg-ribbed-dark" data-example="interpolation">
<div class="row">
<div class="col-md-6 coffeescript-input-column">
<textarea class="coffeescript-input" id="interpolation-coffee">author = "Wittgenstein"
quote = "A picture is a fact. -- #{ author }"
sentence = "#{ 22 / 7 } is a decent approximation of π"
</textarea>
<pre class="placeholder-code"><span class="cm-variable">author</span> <span class="cm-punctuation">=</span> <span class="cm-string">"Wittgenstein"</span>
<span class="cm-variable">quote</span> <span class="cm-punctuation">=</span> <span class="cm-string">"A picture is a fact. -- #{ author }"</span>
<span class="cm-variable">sentence</span> <span class="cm-punctuation">=</span> <span class="cm-string">"#{ 22 / 7 } is a decent approximation of π"</span>
</pre>
</div>
<div class="col-md-6 javascript-output-column">
<textarea class="javascript-output" id="interpolation-js">var author, quote, sentence;
author = "Wittgenstein";
quote = `A picture is a fact. -- ${author}`;
sentence = `${22 / 7} is a decent approximation of π`;
</textarea>
<pre class="placeholder-code"><span class="cm-keyword">var</span> <span class="cm-def">author</span>, <span class="cm-def">quote</span>, <span class="cm-def">sentence</span>;
<span class="cm-variable">author</span> <span class="cm-operator">=</span> <span class="cm-string">"Wittgenstein"</span>;
<span class="cm-variable">quote</span> <span class="cm-operator">=</span> <span class="cm-string-2">`A picture is a fact. -- ${</span><span class="cm-variable">author</span><span class="cm-string-2">}`</span>;
<span class="cm-variable">sentence</span> <span class="cm-operator">=</span> <span class="cm-string-2">`${</span><span class="cm-number">22</span> <span class="cm-operator">/</span> <span class="cm-number">7</span><span class="cm-string-2">}</span> <span class="cm-string-2">is a decent approximation of π`</span>;
</pre>
</div>
</div>
<div class="row">
<div class="col text-right">
<button type="button" class="btn btn-primary" data-action="run-code-example" data-example="interpolation" data-run="sentence"><small><svg class="play-button" viewBox="0 0 24 24">
<path d="M2.56-0.01v24.02L21.44 11.98 2.56-0.01z"></path>
</svg>
</small>sentence</button>
</div>
</div>
</aside>
<p>Multiline strings are allowed in CoffeeScript. Lines are joined by a single space unless they end with a backslash. Indentation is ignored.</p>
<aside class="code-example container-fluid bg-ribbed-dark" data-example="strings">
<div class="row">
<div class="col-md-6 coffeescript-input-column">
<textarea class="coffeescript-input" id="strings-coffee">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..."
</textarea>
<pre class="placeholder-code"><span class="cm-variable">mobyDick</span> <span class="cm-punctuation">=</span> <span class="cm-string">"Call me Ishmael. Some years ago --</span>
<span class="cm-string"> never mind how long precisely -- having little</span>
<span class="cm-string"> or no money in my purse, and nothing particular</span>
<span class="cm-string"> to interest me on shore, I thought I would sail</span>
<span class="cm-string"> about a little and see the watery part of the</span>
<span class="cm-string"> world..."</span>
</pre>
</div>
<div class="col-md-6 javascript-output-column">
<textarea class="javascript-output" id="strings-js">var mobyDick;
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...";
</textarea>
<pre class="placeholder-code"><span class="cm-keyword">var</span> <span class="cm-def">mobyDick</span>;
<span class="cm-variable">mobyDick</span> <span class="cm-operator">=</span> <span class="cm-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>;
</pre>
</div>
</div>
<div class="row">
<div class="col text-right">
<button type="button" class="btn btn-primary" data-action="run-code-example" data-example="strings" data-run="mobyDick"><small><svg class="play-button" viewBox="0 0 24 24">
<path d="M2.56-0.01v24.02L21.44 11.98 2.56-0.01z"></path>
</svg>
</small>mobyDick</button>
</div>
</div>
</aside>
<p>Block strings, delimited by <code>&quot;&quot;&quot;</code> or <code>'''</code>, can be used to hold formatted or indentation-sensitive text (or, if you just dont feel like escaping quotes and apostrophes). The indentation level that begins the block is maintained throughout, so you can keep it all aligned with the body of your code.</p>
<aside class="code-example container-fluid bg-ribbed-dark" data-example="heredocs">
<div class="row">
<div class="col-md-6 coffeescript-input-column">
<textarea class="coffeescript-input" id="heredocs-coffee">html = """
<strong>
cup of coffeescript
</strong>
"""
</textarea>
<pre class="placeholder-code"><span class="cm-variable">html</span> <span class="cm-punctuation">=</span> <span class="cm-string">"""</span>
<span class="cm-string"> &lt;strong></span>
<span class="cm-string"> cup of coffeescript</span>
<span class="cm-string"> &lt;/strong></span>
<span class="cm-string"> """</span>
</pre>
</div>
<div class="col-md-6 javascript-output-column">
<textarea class="javascript-output" id="heredocs-js">var html;
html = "<strong>\n cup of coffeescript\n</strong>";
</textarea>
<pre class="placeholder-code"><span class="cm-keyword">var</span> <span class="cm-def">html</span>;
<span class="cm-variable">html</span> <span class="cm-operator">=</span> <span class="cm-string">"&lt;strong>\n cup of coffeescript\n&lt;/strong>"</span>;
</pre>
</div>
</div>
<div class="row">
<div class="col text-right">
<button type="button" class="btn btn-primary" data-action="run-code-example" data-example="heredocs" data-run="html"><small><svg class="play-button" viewBox="0 0 24 24">
<path d="M2.56-0.01v24.02L21.44 11.98 2.56-0.01z"></path>
</svg>
</small>html</button>
</div>
</div>
</aside>
<p>Double-quoted block strings, like other double-quoted strings, allow interpolation.</p>
</section>
<section id="objects-and-arrays">
<h2>Objects and Arrays</h2>
<p>The CoffeeScript literals for objects and arrays look very similar to their JavaScript cousins. When each property is listed on its own line, the commas are optional. Objects may be created using indentation instead of explicit braces, similar to <a href="http://yaml.org">YAML</a>.</p>
<aside class="code-example container-fluid bg-ribbed-dark" data-example="objects_and_arrays">
<div class="row">
<div class="col-md-6 coffeescript-input-column">
<textarea class="coffeescript-input" id="objects_and_arrays-coffee">song = ["do", "re", "mi", "fa", "so"]
singers = {Jagger: "Rock", Elvis: "Roll"}
bitlist = [
1, 0, 1
0, 0, 1
1, 1, 0
]
kids =
brother:
name: "Max"
age: 11
sister:
name: "Ida"
age: 9
</textarea>
<pre class="placeholder-code"><span class="cm-variable">song</span> <span class="cm-punctuation">=</span> <span class="cm-punctuation">[</span><span class="cm-string">"do"</span><span class="cm-punctuation">,</span> <span class="cm-string">"re"</span><span class="cm-punctuation">,</span> <span class="cm-string">"mi"</span><span class="cm-punctuation">,</span> <span class="cm-string">"fa"</span><span class="cm-punctuation">,</span> <span class="cm-string">"so"</span><span class="cm-punctuation">]</span>
<span class="cm-variable">singers</span> <span class="cm-punctuation">=</span> <span class="cm-punctuation">{</span><span class="cm-variable">Jagger</span><span class="cm-punctuation">:</span> <span class="cm-string">"Rock"</span><span class="cm-punctuation">,</span> <span class="cm-variable">Elvis</span><span class="cm-punctuation">:</span> <span class="cm-string">"Roll"</span><span class="cm-punctuation">}</span>
<span class="cm-variable">bitlist</span> <span class="cm-punctuation">=</span> <span class="cm-punctuation">[</span>
<span class="cm-number">1</span><span class="cm-punctuation">,</span> <span class="cm-number">0</span><span class="cm-punctuation">,</span> <span class="cm-number">1</span>
<span class="cm-number">0</span><span class="cm-punctuation">,</span> <span class="cm-number">0</span><span class="cm-punctuation">,</span> <span class="cm-number">1</span>
<span class="cm-number">1</span><span class="cm-punctuation">,</span> <span class="cm-number">1</span><span class="cm-punctuation">,</span> <span class="cm-number">0</span>
<span class="cm-punctuation">]</span>
<span class="cm-variable">kids</span> <span class="cm-punctuation">=</span>
<span class="cm-indent"> </span><span class="cm-variable">brother</span><span class="cm-punctuation">:</span>
<span class="cm-indent"> </span><span class="cm-variable">name</span><span class="cm-punctuation">:</span> <span class="cm-string">"Max"</span>
<span class="cm-variable">age</span><span class="cm-punctuation">:</span> <span class="cm-number">11</span>
<span class="cm-dedent"> </span><span class="cm-variable">sister</span><span class="cm-punctuation">:</span>
<span class="cm-indent"> </span><span class="cm-variable">name</span><span class="cm-punctuation">:</span> <span class="cm-string">"Ida"</span>
<span class="cm-variable">age</span><span class="cm-punctuation">:</span> <span class="cm-number">9</span>
</pre>
</div>
<div class="col-md-6 javascript-output-column">
<textarea class="javascript-output" id="objects_and_arrays-js">var bitlist, kids, singers, song;
song = ["do", "re", "mi", "fa", "so"];
singers = {
Jagger: "Rock",
Elvis: "Roll"
};
bitlist = [1, 0, 1, 0, 0, 1, 1, 1, 0];
kids = {
brother: {
name: "Max",
age: 11
},
sister: {
name: "Ida",
age: 9
}
};
</textarea>
<pre class="placeholder-code"><span class="cm-keyword">var</span> <span class="cm-def">bitlist</span>, <span class="cm-def">kids</span>, <span class="cm-def">singers</span>, <span class="cm-def">song</span>;
<span class="cm-variable">song</span> <span class="cm-operator">=</span> [<span class="cm-string">"do"</span>, <span class="cm-string">"re"</span>, <span class="cm-string">"mi"</span>, <span class="cm-string">"fa"</span>, <span class="cm-string">"so"</span>];
<span class="cm-variable">singers</span> <span class="cm-operator">=</span> {
<span class="cm-property">Jagger</span>: <span class="cm-string">"Rock"</span>,
<span class="cm-property">Elvis</span>: <span class="cm-string">"Roll"</span>
};
<span class="cm-variable">bitlist</span> <span class="cm-operator">=</span> [<span class="cm-number">1</span>, <span class="cm-number">0</span>, <span class="cm-number">1</span>, <span class="cm-number">0</span>, <span class="cm-number">0</span>, <span class="cm-number">1</span>, <span class="cm-number">1</span>, <span class="cm-number">1</span>, <span class="cm-number">0</span>];
<span class="cm-variable">kids</span> <span class="cm-operator">=</span> {
<span class="cm-property">brother</span>: {
<span class="cm-property">name</span>: <span class="cm-string">"Max"</span>,
<span class="cm-property">age</span>: <span class="cm-number">11</span>
},
<span class="cm-property">sister</span>: {
<span class="cm-property">name</span>: <span class="cm-string">"Ida"</span>,
<span class="cm-property">age</span>: <span class="cm-number">9</span>
}
};
</pre>
</div>
</div>
<div class="row">
<div class="col text-right">
<button type="button" class="btn btn-primary" data-action="run-code-example" data-example="objects_and_arrays" data-run="song.join%28%22%20%u2026%20%22%29"><small><svg class="play-button" viewBox="0 0 24 24">
<path d="M2.56-0.01v24.02L21.44 11.98 2.56-0.01z"></path>
</svg>
</small>song.join(&quot;&quot;)</button>
</div>
</div>
</aside>
<p>CoffeeScript has a shortcut for creating objects when you want the key to be set with a variable of the same name.</p>
<aside class="code-example container-fluid bg-ribbed-dark" data-example="objects_shorthand">
<div class="row">
<div class="col-md-6 coffeescript-input-column">
<textarea class="coffeescript-input" id="objects_shorthand-coffee">name = "Michelangelo"
mask = "orange"
weapon = "nunchuks"
turtle = {name, mask, weapon}
output = "#{turtle.name} wears an #{turtle.mask} mask. Watch out for his #{turtle.weapon}!"
</textarea>
<pre class="placeholder-code"><span class="cm-variable">name</span> <span class="cm-punctuation">=</span> <span class="cm-string">"Michelangelo"</span>
<span class="cm-variable">mask</span> <span class="cm-punctuation">=</span> <span class="cm-string">"orange"</span>
<span class="cm-variable">weapon</span> <span class="cm-punctuation">=</span> <span class="cm-string">"nunchuks"</span>
<span class="cm-variable">turtle</span> <span class="cm-punctuation">=</span> <span class="cm-punctuation">{</span><span class="cm-variable">name</span><span class="cm-punctuation">,</span> <span class="cm-variable">mask</span><span class="cm-punctuation">,</span> <span class="cm-variable">weapon</span><span class="cm-punctuation">}</span>
<span class="cm-variable">output</span> <span class="cm-punctuation">=</span> <span class="cm-string">"#{turtle.name} wears an #{turtle.mask} mask. Watch out for his #{turtle.weapon}!"</span>
</pre>
</div>
<div class="col-md-6 javascript-output-column">
<textarea class="javascript-output" id="objects_shorthand-js">var mask, name, output, turtle, weapon;
name = "Michelangelo";
mask = "orange";
weapon = "nunchuks";
turtle = {name, mask, weapon};
output = `${turtle.name} wears an ${turtle.mask} mask. Watch out for his ${turtle.weapon}!`;
</textarea>
<pre class="placeholder-code"><span class="cm-keyword">var</span> <span class="cm-def">mask</span>, <span class="cm-def">name</span>, <span class="cm-def">output</span>, <span class="cm-def">turtle</span>, <span class="cm-def">weapon</span>;
<span class="cm-variable">name</span> <span class="cm-operator">=</span> <span class="cm-string">"Michelangelo"</span>;
<span class="cm-variable">mask</span> <span class="cm-operator">=</span> <span class="cm-string">"orange"</span>;
<span class="cm-variable">weapon</span> <span class="cm-operator">=</span> <span class="cm-string">"nunchuks"</span>;
<span class="cm-variable">turtle</span> <span class="cm-operator">=</span> {<span class="cm-property">name</span>, <span class="cm-property">mask</span>, <span class="cm-property">weapon</span>};
<span class="cm-variable">output</span> <span class="cm-operator">=</span> <span class="cm-string-2">`${</span><span class="cm-variable">turtle</span>.<span class="cm-property">name</span><span class="cm-string-2">}</span> <span class="cm-string-2">wears an ${</span><span class="cm-variable">turtle</span>.<span class="cm-property">mask</span><span class="cm-string-2">}</span> <span class="cm-string-2">mask. Watch out for his ${</span><span class="cm-variable">turtle</span>.<span class="cm-property">weapon</span><span class="cm-string-2">}!`</span>;
</pre>
</div>
</div>
</aside>
</section>
<section id="comments">
<h2>Comments</h2>
<p>In CoffeeScript, comments are denoted by the <code>#</code> character to the end of a line, or from <code>###</code> to the next appearance of <code>###</code>. Comments are ignored by the compiler, though the compiler makes its best effort at reinserting your comments into the output JavaScript after compilation.</p>
<aside class="code-example container-fluid bg-ribbed-dark" data-example="comment">
<div class="row">
<div class="col-md-6 coffeescript-input-column">
<textarea class="coffeescript-input" id="comment-coffee">###
Fortune Cookie Reader v1.0
Released under the MIT License
###
sayFortune = (fortune) ->
console.log fortune # in bed!
</textarea>
<pre class="placeholder-code"><span class="cm-comment">###</span>
<span class="cm-comment">Fortune Cookie Reader v1.0</span>
<span class="cm-comment">Released under the MIT License</span>
<span class="cm-comment">###</span>
<span class="cm-variable">sayFortune</span> <span class="cm-punctuation">=</span> <span class="cm-punctuation">(</span><span class="cm-variable">fortune</span><span class="cm-punctuation">)</span> <span class="cm-operator">-></span>
<span class="cm-variable">console</span><span class="cm-punctuation">.</span><span class="cm-property">log</span> <span class="cm-variable">fortune</span> <span class="cm-comment"># in bed!</span>
</pre>
</div>
<div class="col-md-6 javascript-output-column">
<textarea class="javascript-output" id="comment-js">/*
Fortune Cookie Reader v1.0
Released under the MIT License
*/
var sayFortune;
sayFortune = function(fortune) {
return console.log(fortune); // in bed!
};
</textarea>
<pre class="placeholder-code"><span class="cm-comment">/*</span>
<span class="cm-comment">Fortune Cookie Reader v1.0</span>
<span class="cm-comment">Released under the MIT License</span>
<span class="cm-comment">*/</span>
<span class="cm-keyword">var</span> <span class="cm-def">sayFortune</span>;
<span class="cm-variable">sayFortune</span> <span class="cm-operator">=</span> <span class="cm-keyword">function</span>(<span class="cm-def">fortune</span>) {
<span class="cm-keyword">return</span> <span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable-2">fortune</span>); <span class="cm-comment">// in bed!</span>
};
</pre>
</div>
</div>
</aside>
<p>Inline <code>###</code> comments make <a href="#type-annotations">type annotations</a> possible.</p>
</section>
<section id="lexical-scope">
<h2>Lexical Scoping and Variable Safety</h2>
<p>The CoffeeScript compiler takes care to make sure that all of your variables are properly declared within lexical scope — you never need to write <code>var</code> yourself.</p>
<aside class="code-example container-fluid bg-ribbed-dark" data-example="scope">
<div class="row">
<div class="col-md-6 coffeescript-input-column">
<textarea class="coffeescript-input" id="scope-coffee">outer = 1
changeNumbers = ->
inner = -1
outer = 10
inner = changeNumbers()
</textarea>
<pre class="placeholder-code"><span class="cm-variable">outer</span> <span class="cm-punctuation">=</span> <span class="cm-number">1</span>
<span class="cm-variable">changeNumbers</span> <span class="cm-punctuation">=</span> <span class="cm-operator">-></span>
<span class="cm-variable">inner</span> <span class="cm-punctuation">=</span> <span class="cm-number">-1</span>
<span class="cm-variable">outer</span> <span class="cm-punctuation">=</span> <span class="cm-number">10</span>
<span class="cm-variable">inner</span> <span class="cm-punctuation">=</span> <span class="cm-variable">changeNumbers</span><span class="cm-punctuation">()</span>
</pre>
</div>
<div class="col-md-6 javascript-output-column">
<textarea class="javascript-output" id="scope-js">var changeNumbers, inner, outer;
outer = 1;
changeNumbers = function() {
var inner;
inner = -1;
return outer = 10;
};
inner = changeNumbers();
</textarea>
<pre class="placeholder-code"><span class="cm-keyword">var</span> <span class="cm-def">changeNumbers</span>, <span class="cm-def">inner</span>, <span class="cm-def">outer</span>;
<span class="cm-variable">outer</span> <span class="cm-operator">=</span> <span class="cm-number">1</span>;
<span class="cm-variable">changeNumbers</span> <span class="cm-operator">=</span> <span class="cm-keyword">function</span>() {
<span class="cm-keyword">var</span> <span class="cm-def">inner</span>;
<span class="cm-variable-2">inner</span> <span class="cm-operator">=</span> <span class="cm-operator">-</span><span class="cm-number">1</span>;
<span class="cm-keyword">return</span> <span class="cm-variable">outer</span> <span class="cm-operator">=</span> <span class="cm-number">10</span>;
};
<span class="cm-variable-2">inner</span> <span class="cm-operator">=</span> <span class="cm-variable">changeNumbers</span>();
</pre>
</div>
</div>
<div class="row">
<div class="col text-right">
<button type="button" class="btn btn-primary" data-action="run-code-example" data-example="scope" data-run="inner"><small><svg class="play-button" viewBox="0 0 24 24">
<path d="M2.56-0.01v24.02L21.44 11.98 2.56-0.01z"></path>
</svg>
</small>inner</button>
</div>
</div>
</aside>
<p>Notice how all of the variable declarations have been pushed up to the top of the closest scope, the first time they appear. <code>outer</code> is not redeclared within the inner function, because its already in scope; <code>inner</code> within the function, on the other hand, should not be able to change the value of the external variable of the same name, and therefore has a declaration of its own.</p>
<p>Because you dont have direct access to the <code>var</code> keyword, its impossible to shadow an outer variable on purpose, you may only refer to it. So be careful that youre not reusing the name of an external variable accidentally, if youre writing a deeply nested function.</p>
<p>Although suppressed within this documentation for clarity, all CoffeeScript output (except in files with <code>import</code> or <code>export</code> statements) is wrapped in an anonymous function: <code>(function(){ … })();</code>. This safety wrapper, combined with the automatic generation of the <code>var</code> keyword, make it exceedingly difficult to pollute the global namespace by accident. (The safety wrapper can be disabled with the <a href="#usage"><code>bare</code> option</a>, and is unnecessary and automatically disabled when using modules.)</p>
<p>If youd like to create top-level variables for other scripts to use, attach them as properties on <code>window</code>; attach them as properties on the <code>exports</code> object in CommonJS; or use an <a href="#modules"><code>export</code> statement</a>. If youre targeting both CommonJS and the browser, the <a href="#existential-operator">existential operator</a> (covered below), gives you a reliable way to figure out where to add them: <code>exports ? this</code>.</p>
<p>Since CoffeeScript takes care of all variable declaration, it is not possible to declare variables with ES2015s <code>let</code> or <code>const</code>. <a href="#unsupported-let-const">This is intentional</a>; we feel that the simplicity gained by not having to think about variable declaration outweighs the benefit of having three separate ways to declare variables.</p>
</section>
<section id="conditionals">
<h2>If, Else, Unless, and Conditional Assignment</h2>
<p><code>if</code>/<code>else</code> statements can be written without the use of parentheses and curly brackets. As with functions and other block expressions, multi-line conditionals are delimited by indentation. Theres also a handy postfix form, with the <code>if</code> or <code>unless</code> at the end.</p>
<p>CoffeeScript can compile <code>if</code> statements into JavaScript expressions, using the ternary operator when possible, and closure wrapping otherwise. There is no explicit ternary statement in CoffeeScript — you simply use a regular <code>if</code> statement on a single line.</p>
<aside class="code-example container-fluid bg-ribbed-dark" data-example="conditionals">
<div class="row">
<div class="col-md-6 coffeescript-input-column">
<textarea class="coffeescript-input" id="conditionals-coffee">mood = greatlyImproved if singing
if happy and knowsIt
clapsHands()
chaChaCha()
else
showIt()
date = if friday then sue else jill
</textarea>
<pre class="placeholder-code"><span class="cm-variable">mood</span> <span class="cm-punctuation">=</span> <span class="cm-variable">greatlyImproved</span> <span class="cm-keyword">if</span> <span class="cm-variable">singing</span>
<span class="cm-keyword">if</span> <span class="cm-variable">happy</span> <span class="cm-operator">and</span> <span class="cm-variable">knowsIt</span>
<span class="cm-variable">clapsHands</span><span class="cm-punctuation">()</span>
<span class="cm-variable">chaChaCha</span><span class="cm-punctuation">()</span>
<span class="cm-keyword">else</span>
<span class="cm-variable">showIt</span><span class="cm-punctuation">()</span>
<span class="cm-variable">date</span> <span class="cm-punctuation">=</span> <span class="cm-keyword">if</span> <span class="cm-variable">friday</span> <span class="cm-keyword">then</span> <span class="cm-variable">sue</span> <span class="cm-keyword">else</span> <span class="cm-variable">jill</span>
</pre>
</div>
<div class="col-md-6 javascript-output-column">
<textarea class="javascript-output" id="conditionals-js">var date, mood;
if (singing) {
mood = greatlyImproved;
}
if (happy && knowsIt) {
clapsHands();
chaChaCha();
} else {
showIt();
}
date = friday ? sue : jill;
</textarea>
<pre class="placeholder-code"><span class="cm-keyword">var</span> <span class="cm-def">date</span>, <span class="cm-def">mood</span>;
<span class="cm-keyword">if</span> (<span class="cm-variable">singing</span>) {
<span class="cm-variable">mood</span> <span class="cm-operator">=</span> <span class="cm-variable">greatlyImproved</span>;
}
<span class="cm-keyword">if</span> (<span class="cm-variable">happy</span> <span class="cm-operator">&amp;&amp;</span> <span class="cm-variable">knowsIt</span>) {
<span class="cm-variable">clapsHands</span>();
<span class="cm-variable">chaChaCha</span>();
} <span class="cm-keyword">else</span> {
<span class="cm-variable">showIt</span>();
}
<span class="cm-variable">date</span> <span class="cm-operator">=</span> <span class="cm-variable">friday</span> <span class="cm-operator">?</span> <span class="cm-variable">sue</span> : <span class="cm-variable">jill</span>;
</pre>
</div>
</div>
</aside>
</section>
<section id="splats">
<h2>Splats, or Rest Parameters/Spread Syntax</h2>
<p>The JavaScript <code>arguments</code> object is a useful way to work with functions that accept variable numbers of arguments. CoffeeScript provides splats <code>...</code>, both for function definition as well as invocation, making variable numbers of arguments a little bit more palatable. ES2015 adopted this feature as their <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters">rest parameters</a>.</p>
<aside class="code-example container-fluid bg-ribbed-dark" data-example="splats">
<div class="row">
<div class="col-md-6 coffeescript-input-column">
<textarea class="coffeescript-input" id="splats-coffee">gold = silver = rest = "unknown"
awardMedals = (first, second, others...) ->
gold = first
silver = second
rest = others
contenders = [
"Michael Phelps"
"Liu Xiang"
"Yao Ming"
"Allyson Felix"
"Shawn Johnson"
"Roman Sebrle"
"Guo Jingjing"
"Tyson Gay"
"Asafa Powell"
"Usain Bolt"
]
awardMedals contenders...
alert """
Gold: #{gold}
Silver: #{silver}
The Field: #{rest.join ', '}
"""
</textarea>
<pre class="placeholder-code"><span class="cm-variable">gold</span> <span class="cm-punctuation">=</span> <span class="cm-variable">silver</span> <span class="cm-punctuation">=</span> <span class="cm-variable">rest</span> <span class="cm-punctuation">=</span> <span class="cm-string">"unknown"</span>
<span class="cm-variable">awardMedals</span> <span class="cm-punctuation">=</span> <span class="cm-punctuation">(</span><span class="cm-variable">first</span><span class="cm-punctuation">,</span> <span class="cm-variable">second</span><span class="cm-punctuation">,</span> <span class="cm-variable">others</span><span class="cm-punctuation">...)</span> <span class="cm-operator">-></span>
<span class="cm-variable">gold</span> <span class="cm-punctuation">=</span> <span class="cm-variable">first</span>
<span class="cm-variable">silver</span> <span class="cm-punctuation">=</span> <span class="cm-variable">second</span>
<span class="cm-variable">rest</span> <span class="cm-punctuation">=</span> <span class="cm-variable">others</span>
<span class="cm-variable">contenders</span> <span class="cm-punctuation">=</span> <span class="cm-punctuation">[</span>
<span class="cm-string">"Michael Phelps"</span>
<span class="cm-string">"Liu Xiang"</span>
<span class="cm-string">"Yao Ming"</span>
<span class="cm-string">"Allyson Felix"</span>
<span class="cm-string">"Shawn Johnson"</span>
<span class="cm-string">"Roman Sebrle"</span>
<span class="cm-string">"Guo Jingjing"</span>
<span class="cm-string">"Tyson Gay"</span>
<span class="cm-string">"Asafa Powell"</span>
<span class="cm-string">"Usain Bolt"</span>
<span class="cm-punctuation">]</span>
<span class="cm-variable">awardMedals</span> <span class="cm-variable">contenders</span><span class="cm-punctuation">...</span>
<span class="cm-variable">alert</span> <span class="cm-string">"""</span>
<span class="cm-string">Gold: #{gold}</span>
<span class="cm-string">Silver: #{silver}</span>
<span class="cm-string">The Field: #{rest.join ', '}</span>
<span class="cm-string">"""</span>
</pre>
</div>
<div class="col-md-6 javascript-output-column">
<textarea class="javascript-output" id="splats-js">var awardMedals, contenders, gold, rest, silver;
gold = silver = rest = "unknown";
awardMedals = function(first, second, ...others) {
gold = first;
silver = second;
return rest = others;
};
contenders = ["Michael Phelps", "Liu Xiang", "Yao Ming", "Allyson Felix", "Shawn Johnson", "Roman Sebrle", "Guo Jingjing", "Tyson Gay", "Asafa Powell", "Usain Bolt"];
awardMedals(...contenders);
alert(`Gold: ${gold}\nSilver: ${silver}\nThe Field: ${rest.join(', ')}`);
</textarea>
<pre class="placeholder-code"><span class="cm-keyword">var</span> <span class="cm-def">awardMedals</span>, <span class="cm-def">contenders</span>, <span class="cm-def">gold</span>, <span class="cm-def">rest</span>, <span class="cm-def">silver</span>;
<span class="cm-variable">gold</span> <span class="cm-operator">=</span> <span class="cm-variable">silver</span> <span class="cm-operator">=</span> <span class="cm-variable">rest</span> <span class="cm-operator">=</span> <span class="cm-string">"unknown"</span>;
<span class="cm-variable">awardMedals</span> <span class="cm-operator">=</span> <span class="cm-keyword">function</span>(<span class="cm-def">first</span>, <span class="cm-def">second</span>, <span class="cm-meta">...</span><span class="cm-def">others</span>) {
<span class="cm-variable">gold</span> <span class="cm-operator">=</span> <span class="cm-variable-2">first</span>;
<span class="cm-variable">silver</span> <span class="cm-operator">=</span> <span class="cm-variable-2">second</span>;
<span class="cm-keyword">return</span> <span class="cm-variable">rest</span> <span class="cm-operator">=</span> <span class="cm-variable-2">others</span>;
};
<span class="cm-variable">contenders</span> <span class="cm-operator">=</span> [<span class="cm-string">"Michael Phelps"</span>, <span class="cm-string">"Liu Xiang"</span>, <span class="cm-string">"Yao Ming"</span>, <span class="cm-string">"Allyson Felix"</span>, <span class="cm-string">"Shawn Johnson"</span>, <span class="cm-string">"Roman Sebrle"</span>, <span class="cm-string">"Guo Jingjing"</span>, <span class="cm-string">"Tyson Gay"</span>, <span class="cm-string">"Asafa Powell"</span>, <span class="cm-string">"Usain Bolt"</span>];
<span class="cm-variable">awardMedals</span>(<span class="cm-meta">...</span><span class="cm-variable">contenders</span>);
<span class="cm-variable">alert</span>(<span class="cm-string-2">`Gold: ${</span><span class="cm-variable">gold</span><span class="cm-string-2">}\nSilver: ${</span><span class="cm-variable">silver</span><span class="cm-string-2">}\nThe Field: ${</span><span class="cm-variable">rest</span>.<span class="cm-property">join</span>(<span class="cm-string">', '</span>)<span class="cm-string-2">}`</span>);
</pre>
</div>
</div>
<div class="row">
<div class="col text-right">
<button type="button" class="btn btn-primary" data-action="run-code-example" data-example="splats" data-run="true"><small><svg class="play-button" viewBox="0 0 24 24">
<path d="M2.56-0.01v24.02L21.44 11.98 2.56-0.01z"></path>
</svg>
</small></button>
</div>
</div>
</aside>
<div id="array-spread" class="bookmark"></div>
<p>Splats also let us elide array elements…</p>
<aside class="code-example container-fluid bg-ribbed-dark" data-example="array_spread">
<div class="row">
<div class="col-md-6 coffeescript-input-column">
<textarea class="coffeescript-input" id="array_spread-coffee">popular = ['pepperoni', 'sausage', 'cheese']
unwanted = ['anchovies', 'olives']
all = [popular..., unwanted..., 'mushrooms']
</textarea>
<pre class="placeholder-code"><span class="cm-variable">popular</span> <span class="cm-punctuation">=</span> <span class="cm-punctuation">[</span><span class="cm-string">'pepperoni'</span><span class="cm-punctuation">,</span> <span class="cm-string">'sausage'</span><span class="cm-punctuation">,</span> <span class="cm-string">'cheese'</span><span class="cm-punctuation">]</span>
<span class="cm-variable">unwanted</span> <span class="cm-punctuation">=</span> <span class="cm-punctuation">[</span><span class="cm-string">'anchovies'</span><span class="cm-punctuation">,</span> <span class="cm-string">'olives'</span><span class="cm-punctuation">]</span>
<span class="cm-variable">all</span> <span class="cm-punctuation">=</span> <span class="cm-punctuation">[</span><span class="cm-variable">popular</span><span class="cm-punctuation">...,</span> <span class="cm-variable">unwanted</span><span class="cm-punctuation">...,</span> <span class="cm-string">'mushrooms'</span><span class="cm-punctuation">]</span>
</pre>
</div>
<div class="col-md-6 javascript-output-column">
<textarea class="javascript-output" id="array_spread-js">var all, popular, unwanted;
popular = ['pepperoni', 'sausage', 'cheese'];
unwanted = ['anchovies', 'olives'];
all = [...popular, ...unwanted, 'mushrooms'];
</textarea>
<pre class="placeholder-code"><span class="cm-keyword">var</span> <span class="cm-def">all</span>, <span class="cm-def">popular</span>, <span class="cm-def">unwanted</span>;
<span class="cm-variable">popular</span> <span class="cm-operator">=</span> [<span class="cm-string">'pepperoni'</span>, <span class="cm-string">'sausage'</span>, <span class="cm-string">'cheese'</span>];
<span class="cm-variable">unwanted</span> <span class="cm-operator">=</span> [<span class="cm-string">'anchovies'</span>, <span class="cm-string">'olives'</span>];
<span class="cm-variable">all</span> <span class="cm-operator">=</span> [<span class="cm-meta">...</span><span class="cm-variable">popular</span>, <span class="cm-meta">...</span><span class="cm-variable">unwanted</span>, <span class="cm-string">'mushrooms'</span>];
</pre>
</div>
</div>
<div class="row">
<div class="col text-right">
<button type="button" class="btn btn-primary" data-action="run-code-example" data-example="array_spread" data-run="all"><small><svg class="play-button" viewBox="0 0 24 24">
<path d="M2.56-0.01v24.02L21.44 11.98 2.56-0.01z"></path>
</svg>
</small>all</button>
</div>
</div>
</aside>
<div id="object-spread" class="bookmark"></div>
<p>…and object properties.</p>
<aside class="code-example container-fluid bg-ribbed-dark" data-example="object_spread">
<div class="row">
<div class="col-md-6 coffeescript-input-column">
<textarea class="coffeescript-input" id="object_spread-coffee">user =
name: 'Werner Heisenberg'
occupation: 'theoretical physicist'
currentUser = { user..., status: 'Uncertain' }
</textarea>
<pre class="placeholder-code"><span class="cm-variable">user</span> <span class="cm-punctuation">=</span>
<span class="cm-indent"> </span><span class="cm-variable">name</span><span class="cm-punctuation">:</span> <span class="cm-string">'Werner Heisenberg'</span>
<span class="cm-variable">occupation</span><span class="cm-punctuation">:</span> <span class="cm-string">'theoretical physicist'</span>
<span class="cm-variable">currentUser</span> <span class="cm-punctuation">=</span> <span class="cm-punctuation">{</span> <span class="cm-variable">user</span><span class="cm-punctuation">...,</span> <span class="cm-variable">status</span><span class="cm-punctuation">:</span> <span class="cm-string">'Uncertain'</span> <span class="cm-punctuation">}</span>
</pre>
</div>
<div class="col-md-6 javascript-output-column">
<textarea class="javascript-output" id="object_spread-js">var currentUser, user;
user = {
name: 'Werner Heisenberg',
occupation: 'theoretical physicist'
};
currentUser = {
...user,
status: 'Uncertain'
};
</textarea>
<pre class="placeholder-code"><span class="cm-keyword">var</span> <span class="cm-def">currentUser</span>, <span class="cm-def">user</span>;
<span class="cm-variable">user</span> <span class="cm-operator">=</span> {
<span class="cm-property">name</span>: <span class="cm-string">'Werner Heisenberg'</span>,
<span class="cm-property">occupation</span>: <span class="cm-string">'theoretical physicist'</span>
};
<span class="cm-variable">currentUser</span> <span class="cm-operator">=</span> {
<span class="cm-meta">...</span><span class="cm-variable">user</span>,
<span class="cm-property">status</span>: <span class="cm-string">'Uncertain'</span>
};
</pre>
</div>
</div>
<div class="row">
<div class="col text-right">
<button type="button" class="btn btn-primary" data-action="run-code-example" data-example="object_spread" data-run="JSON.stringify%28currentUser%29"><small><svg class="play-button" viewBox="0 0 24 24">
<path d="M2.56-0.01v24.02L21.44 11.98 2.56-0.01z"></path>
</svg>
</small>JSON.stringify(currentUser)</button>
</div>
</div>
</aside>
<p>In ECMAScript this is called <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator">spread syntax</a>, and has been supported for arrays since ES2015 and objects since ES2018.</p>
</section>
<section id="loops">
<h2>Loops and Comprehensions</h2>
<p>Most of the loops youll write in CoffeeScript will be <strong>comprehensions</strong> over arrays, objects, and ranges. Comprehensions replace (and compile into) <code>for</code> loops, with optional guard clauses and the value of the current array index. Unlike for loops, array comprehensions are expressions, and can be returned and assigned.</p>
<aside class="code-example container-fluid bg-ribbed-dark" data-example="array_comprehensions">
<div class="row">
<div class="col-md-6 coffeescript-input-column">
<textarea class="coffeescript-input" id="array_comprehensions-coffee"># Eat lunch.
eat = (food) -> "#{food} eaten."
eat food for food in ['toast', 'cheese', 'wine']
# Fine five course dining.
courses = ['greens', 'caviar', 'truffles', 'roast', 'cake']
menu = (i, dish) -> "Menu Item #{i}: #{dish}"
menu i + 1, dish for dish, i in courses
# Health conscious meal.
foods = ['broccoli', 'spinach', 'chocolate']
eat food for food in foods when food isnt 'chocolate'
</textarea>
<pre class="placeholder-code"><span class="cm-comment"># Eat lunch.</span>
<span class="cm-variable">eat</span> <span class="cm-punctuation">=</span> <span class="cm-punctuation">(</span><span class="cm-variable">food</span><span class="cm-punctuation">)</span> <span class="cm-operator">-></span> <span class="cm-string">"#{food} eaten."</span>
<span class="cm-variable">eat</span> <span class="cm-variable">food</span> <span class="cm-keyword">for</span> <span class="cm-variable">food</span> <span class="cm-operator">in</span> <span class="cm-punctuation">[</span><span class="cm-string">'toast'</span><span class="cm-punctuation">,</span> <span class="cm-string">'cheese'</span><span class="cm-punctuation">,</span> <span class="cm-string">'wine'</span><span class="cm-punctuation">]</span>
<span class="cm-comment"># Fine five course dining.</span>
<span class="cm-variable">courses</span> <span class="cm-punctuation">=</span> <span class="cm-punctuation">[</span><span class="cm-string">'greens'</span><span class="cm-punctuation">,</span> <span class="cm-string">'caviar'</span><span class="cm-punctuation">,</span> <span class="cm-string">'truffles'</span><span class="cm-punctuation">,</span> <span class="cm-string">'roast'</span><span class="cm-punctuation">,</span> <span class="cm-string">'cake'</span><span class="cm-punctuation">]</span>
<span class="cm-variable">menu</span> <span class="cm-punctuation">=</span> <span class="cm-punctuation">(</span><span class="cm-variable">i</span><span class="cm-punctuation">,</span> <span class="cm-variable">dish</span><span class="cm-punctuation">)</span> <span class="cm-operator">-></span> <span class="cm-string">"Menu Item #{i}: #{dish}"</span>
<span class="cm-variable">menu</span> <span class="cm-variable">i</span> <span class="cm-operator">+</span> <span class="cm-number">1</span><span class="cm-punctuation">,</span> <span class="cm-variable">dish</span> <span class="cm-keyword">for</span> <span class="cm-variable">dish</span><span class="cm-punctuation">,</span> <span class="cm-variable">i</span> <span class="cm-operator">in</span> <span class="cm-variable">courses</span>
<span class="cm-comment"># Health conscious meal.</span>
<span class="cm-variable">foods</span> <span class="cm-punctuation">=</span> <span class="cm-punctuation">[</span><span class="cm-string">'broccoli'</span><span class="cm-punctuation">,</span> <span class="cm-string">'spinach'</span><span class="cm-punctuation">,</span> <span class="cm-string">'chocolate'</span><span class="cm-punctuation">]</span>
<span class="cm-variable">eat</span> <span class="cm-variable">food</span> <span class="cm-keyword">for</span> <span class="cm-variable">food</span> <span class="cm-operator">in</span> <span class="cm-variable">foods</span> <span class="cm-keyword">when</span> <span class="cm-variable">food</span> <span class="cm-operator">isnt</span> <span class="cm-string">'chocolate'</span>
</pre>
</div>
<div class="col-md-6 javascript-output-column">
<textarea class="javascript-output" id="array_comprehensions-js">// Eat lunch.
var courses, dish, eat, food, foods, i, j, k, l, len, len1, len2, menu, ref;
eat = function(food) {
return `${food} eaten.`;
};
ref = ['toast', 'cheese', 'wine'];
for (j = 0, len = ref.length; j < len; j++) {
food = ref[j];
eat(food);
}
// Fine five course dining.
courses = ['greens', 'caviar', 'truffles', 'roast', 'cake'];
menu = function(i, dish) {
return `Menu Item ${i}: ${dish}`;
};
for (i = k = 0, len1 = courses.length; k < len1; i = ++k) {
dish = courses[i];
menu(i + 1, dish);
}
// Health conscious meal.
foods = ['broccoli', 'spinach', 'chocolate'];
for (l = 0, len2 = foods.length; l < len2; l++) {
food = foods[l];
if (food !== 'chocolate') {
eat(food);
}
}
</textarea>
<pre class="placeholder-code"><span class="cm-comment">// Eat lunch.</span>
<span class="cm-keyword">var</span> <span class="cm-def">courses</span>, <span class="cm-def">dish</span>, <span class="cm-def">eat</span>, <span class="cm-def">food</span>, <span class="cm-def">foods</span>, <span class="cm-def">i</span>, <span class="cm-def">j</span>, <span class="cm-def">k</span>, <span class="cm-def">l</span>, <span class="cm-def">len</span>, <span class="cm-def">len1</span>, <span class="cm-def">len2</span>, <span class="cm-def">menu</span>, <span class="cm-def">ref</span>;
<span class="cm-variable">eat</span> <span class="cm-operator">=</span> <span class="cm-keyword">function</span>(<span class="cm-def">food</span>) {
<span class="cm-keyword">return</span> <span class="cm-string-2">`${</span><span class="cm-variable-2">food</span><span class="cm-string-2">}</span> <span class="cm-string-2">eaten.`</span>;
};
<span class="cm-variable">ref</span> <span class="cm-operator">=</span> [<span class="cm-string">'toast'</span>, <span class="cm-string">'cheese'</span>, <span class="cm-string">'wine'</span>];
<span class="cm-keyword">for</span> (<span class="cm-variable">j</span> <span class="cm-operator">=</span> <span class="cm-number">0</span>, <span class="cm-variable">len</span> <span class="cm-operator">=</span> <span class="cm-variable">ref</span>.<span class="cm-property">length</span>; <span class="cm-variable">j</span> <span class="cm-operator">&lt;</span> <span class="cm-variable">len</span>; <span class="cm-variable">j</span><span class="cm-operator">++</span>) {
<span class="cm-variable">food</span> <span class="cm-operator">=</span> <span class="cm-variable">ref</span>[<span class="cm-variable">j</span>];
<span class="cm-variable">eat</span>(<span class="cm-variable">food</span>);
}
<span class="cm-comment">// Fine five course dining.</span>
<span class="cm-variable">courses</span> <span class="cm-operator">=</span> [<span class="cm-string">'greens'</span>, <span class="cm-string">'caviar'</span>, <span class="cm-string">'truffles'</span>, <span class="cm-string">'roast'</span>, <span class="cm-string">'cake'</span>];
<span class="cm-variable">menu</span> <span class="cm-operator">=</span> <span class="cm-keyword">function</span>(<span class="cm-def">i</span>, <span class="cm-def">dish</span>) {
<span class="cm-keyword">return</span> <span class="cm-string-2">`Menu Item ${</span><span class="cm-variable-2">i</span><span class="cm-string-2">}: ${</span><span class="cm-variable-2">dish</span><span class="cm-string-2">}`</span>;
};
<span class="cm-keyword">for</span> (<span class="cm-variable">i</span> <span class="cm-operator">=</span> <span class="cm-variable">k</span> <span class="cm-operator">=</span> <span class="cm-number">0</span>, <span class="cm-variable">len1</span> <span class="cm-operator">=</span> <span class="cm-variable">courses</span>.<span class="cm-property">length</span>; <span class="cm-variable">k</span> <span class="cm-operator">&lt;</span> <span class="cm-variable">len1</span>; <span class="cm-variable">i</span> <span class="cm-operator">=</span> <span class="cm-operator">++</span><span class="cm-variable">k</span>) {
<span class="cm-variable">dish</span> <span class="cm-operator">=</span> <span class="cm-variable">courses</span>[<span class="cm-variable">i</span>];
<span class="cm-variable">menu</span>(<span class="cm-variable">i</span> <span class="cm-operator">+</span> <span class="cm-number">1</span>, <span class="cm-variable">dish</span>);
}
<span class="cm-comment">// Health conscious meal.</span>
<span class="cm-variable">foods</span> <span class="cm-operator">=</span> [<span class="cm-string">'broccoli'</span>, <span class="cm-string">'spinach'</span>, <span class="cm-string">'chocolate'</span>];
<span class="cm-keyword">for</span> (<span class="cm-variable">l</span> <span class="cm-operator">=</span> <span class="cm-number">0</span>, <span class="cm-variable">len2</span> <span class="cm-operator">=</span> <span class="cm-variable">foods</span>.<span class="cm-property">length</span>; <span class="cm-variable">l</span> <span class="cm-operator">&lt;</span> <span class="cm-variable">len2</span>; <span class="cm-variable">l</span><span class="cm-operator">++</span>) {
<span class="cm-variable">food</span> <span class="cm-operator">=</span> <span class="cm-variable">foods</span>[<span class="cm-variable">l</span>];
<span class="cm-keyword">if</span> (<span class="cm-variable">food</span> <span class="cm-operator">!==</span> <span class="cm-string">'chocolate'</span>) {
<span class="cm-variable">eat</span>(<span class="cm-variable">food</span>);
}
}
</pre>
</div>
</div>
</aside>
<p>Comprehensions should be able to handle most places where you otherwise would use a loop, <code>each</code>/<code>forEach</code>, <code>map</code>, or <code>select</code>/<code>filter</code>, for example:<br>
<code>shortNames = (name for name in list when name.length &lt; 5)</code><br>
If you know the start and end of your loop, or would like to step through in fixed-size increments, you can use a range to specify the start and end of your comprehension.</p>
<aside class="code-example container-fluid bg-ribbed-dark" data-example="range_comprehensions">
<div class="row">
<div class="col-md-6 coffeescript-input-column">
<textarea class="coffeescript-input" id="range_comprehensions-coffee">countdown = (num for num in [10..1])
</textarea>
<pre class="placeholder-code"><span class="cm-variable">countdown</span> <span class="cm-punctuation">=</span> <span class="cm-punctuation">(</span><span class="cm-variable">num</span> <span class="cm-keyword">for</span> <span class="cm-variable">num</span> <span class="cm-operator">in</span> <span class="cm-punctuation">[</span><span class="cm-number">10..1</span><span class="cm-punctuation">])</span>
</pre>
</div>
<div class="col-md-6 javascript-output-column">
<textarea class="javascript-output" id="range_comprehensions-js">var countdown, num;
countdown = (function() {
var i, results;
results = [];
for (num = i = 10; i >= 1; num = --i) {
results.push(num);
}
return results;
})();
</textarea>
<pre class="placeholder-code"><span class="cm-keyword">var</span> <span class="cm-def">countdown</span>, <span class="cm-def">num</span>;
<span class="cm-variable">countdown</span> <span class="cm-operator">=</span> (<span class="cm-keyword">function</span>() {
<span class="cm-keyword">var</span> <span class="cm-def">i</span>, <span class="cm-def">results</span>;
<span class="cm-variable-2">results</span> <span class="cm-operator">=</span> [];
<span class="cm-keyword">for</span> (<span class="cm-variable">num</span> <span class="cm-operator">=</span> <span class="cm-variable-2">i</span> <span class="cm-operator">=</span> <span class="cm-number">10</span>; <span class="cm-variable-2">i</span> <span class="cm-operator">>=</span> <span class="cm-number">1</span>; <span class="cm-variable">num</span> <span class="cm-operator">=</span> <span class="cm-operator">--</span><span class="cm-variable-2">i</span>) {
<span class="cm-variable-2">results</span>.<span class="cm-property">push</span>(<span class="cm-variable">num</span>);
}
<span class="cm-keyword">return</span> <span class="cm-variable-2">results</span>;
})();
</pre>
</div>
</div>
<div class="row">
<div class="col text-right">
<button type="button" class="btn btn-primary" data-action="run-code-example" data-example="range_comprehensions" data-run="countdown"><small><svg class="play-button" viewBox="0 0 24 24">
<path d="M2.56-0.01v24.02L21.44 11.98 2.56-0.01z"></path>
</svg>
</small>countdown</button>
</div>
</div>
</aside>
<p>Note how because we are assigning the value of the comprehensions to a variable in the example above, CoffeeScript is collecting the result of each iteration into an array. Sometimes functions end with loops that are intended to run only for their side-effects. Be careful that youre not accidentally returning the results of the comprehension in these cases, by adding a meaningful return value — like <code>true</code> — or <code>null</code>, to the bottom of your function.</p>
<p>To step through a range comprehension in fixed-size chunks, use <code>by</code>, for example:
<code>evens = (x for x in [0..10] by 2)</code></p>
<p>If you dont need the current iteration value you may omit it:
<code>browser.closeCurrentTab() for [0...count]</code></p>
<p>Comprehensions can also be used to iterate over the keys and values in an object. Use <code>of</code> to signal comprehension over the properties of an object instead of the values in an array.</p>
<aside class="code-example container-fluid bg-ribbed-dark" data-example="object_comprehensions">
<div class="row">
<div class="col-md-6 coffeescript-input-column">
<textarea class="coffeescript-input" id="object_comprehensions-coffee">yearsOld = max: 10, ida: 9, tim: 11
ages = for child, age of yearsOld
"#{child} is #{age}"
</textarea>
<pre class="placeholder-code"><span class="cm-variable">yearsOld</span> <span class="cm-punctuation">=</span> <span class="cm-variable">max</span><span class="cm-punctuation">:</span> <span class="cm-number">10</span><span class="cm-punctuation">,</span> <span class="cm-variable">ida</span><span class="cm-punctuation">:</span> <span class="cm-number">9</span><span class="cm-punctuation">,</span> <span class="cm-variable">tim</span><span class="cm-punctuation">:</span> <span class="cm-number">11</span>
<span class="cm-variable">ages</span> <span class="cm-punctuation">=</span> <span class="cm-keyword">for</span> <span class="cm-variable">child</span><span class="cm-punctuation">,</span> <span class="cm-variable">age</span> <span class="cm-keyword">of</span> <span class="cm-variable">yearsOld</span>
<span class="cm-string">"#{child} is #{age}"</span>
</pre>
</div>
<div class="col-md-6 javascript-output-column">
<textarea class="javascript-output" id="object_comprehensions-js">var age, ages, child, yearsOld;
yearsOld = {
max: 10,
ida: 9,
tim: 11
};
ages = (function() {
var results;
results = [];
for (child in yearsOld) {
age = yearsOld[child];
results.push(`${child} is ${age}`);
}
return results;
})();
</textarea>
<pre class="placeholder-code"><span class="cm-keyword">var</span> <span class="cm-def">age</span>, <span class="cm-def">ages</span>, <span class="cm-def">child</span>, <span class="cm-def">yearsOld</span>;
<span class="cm-variable">yearsOld</span> <span class="cm-operator">=</span> {
<span class="cm-property">max</span>: <span class="cm-number">10</span>,
<span class="cm-property">ida</span>: <span class="cm-number">9</span>,
<span class="cm-property">tim</span>: <span class="cm-number">11</span>
};
<span class="cm-variable">ages</span> <span class="cm-operator">=</span> (<span class="cm-keyword">function</span>() {
<span class="cm-keyword">var</span> <span class="cm-def">results</span>;
<span class="cm-variable-2">results</span> <span class="cm-operator">=</span> [];
<span class="cm-keyword">for</span> (<span class="cm-variable">child</span> <span class="cm-keyword">in</span> <span class="cm-variable">yearsOld</span>) {
<span class="cm-variable">age</span> <span class="cm-operator">=</span> <span class="cm-variable">yearsOld</span>[<span class="cm-variable">child</span>];
<span class="cm-variable-2">results</span>.<span class="cm-property">push</span>(<span class="cm-string-2">`${</span><span class="cm-variable">child</span><span class="cm-string-2">}</span> <span class="cm-string-2">is ${</span><span class="cm-variable">age</span><span class="cm-string-2">}`</span>);
}
<span class="cm-keyword">return</span> <span class="cm-variable-2">results</span>;
})();
</pre>
</div>
</div>
<div class="row">
<div class="col text-right">
<button type="button" class="btn btn-primary" data-action="run-code-example" data-example="object_comprehensions" data-run="ages.join%28%22%2C%20%22%29"><small><svg class="play-button" viewBox="0 0 24 24">
<path d="M2.56-0.01v24.02L21.44 11.98 2.56-0.01z"></path>
</svg>
</small>ages.join(&quot;, &quot;)</button>
</div>
</div>
</aside>
<p>If you would like to iterate over just the keys that are defined on the object itself, by adding a <code>hasOwnProperty</code> check to avoid properties that may be inherited from the prototype, use <code>for own key, value of object</code>.</p>
<p>To iterate a generator function, use <code>from</code>. See <a href="#generator-iteration">Generator Functions</a>.</p>
<p>The only low-level loop that CoffeeScript provides is the <code>while</code> loop. The main difference from JavaScript is that the <code>while</code> loop can be used as an expression, returning an array containing the result of each iteration through the loop.</p>
<aside class="code-example container-fluid bg-ribbed-dark" data-example="while">
<div class="row">
<div class="col-md-6 coffeescript-input-column">
<textarea class="coffeescript-input" id="while-coffee"># Econ 101
if this.studyingEconomics
buy() while supply > demand
sell() until supply > demand
# Nursery Rhyme
num = 6
lyrics = while num -= 1
"#{num} little monkeys, jumping on the bed.
One fell out and bumped his head."
</textarea>
<pre class="placeholder-code"><span class="cm-comment"># Econ 101</span>
<span class="cm-keyword">if</span> <span class="cm-keyword">this</span><span class="cm-punctuation">.</span><span class="cm-property">studyingEconomics</span>
<span class="cm-variable">buy</span><span class="cm-punctuation">()</span> <span class="cm-keyword">while</span> <span class="cm-variable">supply</span> <span class="cm-operator">></span> <span class="cm-variable">demand</span>
<span class="cm-dedent"> </span><span class="cm-variable">sell</span><span class="cm-punctuation">()</span> <span class="cm-keyword">until</span> <span class="cm-variable">supply</span> <span class="cm-operator">></span> <span class="cm-variable">demand</span>
<span class="cm-comment"># Nursery Rhyme</span>
<span class="cm-variable">num</span> <span class="cm-punctuation">=</span> <span class="cm-number">6</span>
<span class="cm-variable">lyrics</span> <span class="cm-punctuation">=</span> <span class="cm-keyword">while</span> <span class="cm-variable">num</span> <span class="cm-operator">-=</span> <span class="cm-number">1</span>
<span class="cm-string">"#{num} little monkeys, jumping on the bed.</span>
<span class="cm-string"> One fell out and bumped his head."</span>
</pre>
</div>
<div class="col-md-6 javascript-output-column">
<textarea class="javascript-output" id="while-js">// Econ 101
var lyrics, num;
if (this.studyingEconomics) {
while (supply > demand) {
buy();
}
while (!(supply > demand)) {
sell();
}
}
// Nursery Rhyme
num = 6;
lyrics = (function() {
var results;
results = [];
while (num -= 1) {
results.push(`${num} little monkeys, jumping on the bed. One fell out and bumped his head.`);
}
return results;
})();
</textarea>
<pre class="placeholder-code"><span class="cm-comment">// Econ 101</span>
<span class="cm-keyword">var</span> <span class="cm-def">lyrics</span>, <span class="cm-def">num</span>;
<span class="cm-keyword">if</span> (<span class="cm-keyword">this</span>.<span class="cm-property">studyingEconomics</span>) {
<span class="cm-keyword">while</span> (<span class="cm-variable">supply</span> <span class="cm-operator">></span> <span class="cm-variable">demand</span>) {
<span class="cm-variable">buy</span>();
}
<span class="cm-keyword">while</span> (<span class="cm-operator">!</span>(<span class="cm-variable">supply</span> <span class="cm-operator">></span> <span class="cm-variable">demand</span>)) {
<span class="cm-variable">sell</span>();
}
}
<span class="cm-comment">// Nursery Rhyme</span>
<span class="cm-variable">num</span> <span class="cm-operator">=</span> <span class="cm-number">6</span>;
<span class="cm-variable">lyrics</span> <span class="cm-operator">=</span> (<span class="cm-keyword">function</span>() {
<span class="cm-keyword">var</span> <span class="cm-def">results</span>;
<span class="cm-variable-2">results</span> <span class="cm-operator">=</span> [];
<span class="cm-keyword">while</span> (<span class="cm-variable">num</span> <span class="cm-operator">-=</span> <span class="cm-number">1</span>) {
<span class="cm-variable-2">results</span>.<span class="cm-property">push</span>(<span class="cm-string-2">`${</span><span class="cm-variable">num</span><span class="cm-string-2">}</span> <span class="cm-string-2">little monkeys, jumping on the bed. One fell out and bumped his head.`</span>);
}
<span class="cm-keyword">return</span> <span class="cm-variable-2">results</span>;
})();
</pre>
</div>
</div>
<div class="row">
<div class="col text-right">
<button type="button" class="btn btn-primary" data-action="run-code-example" data-example="while" data-run="lyrics.join%28%22%5Cn%22%29"><small><svg class="play-button" viewBox="0 0 24 24">
<path d="M2.56-0.01v24.02L21.44 11.98 2.56-0.01z"></path>
</svg>
</small>lyrics.join(&quot;\n&quot;)</button>
</div>
</div>
</aside>
<p>For readability, the <code>until</code> keyword is equivalent to <code>while not</code>, and the <code>loop</code> keyword is equivalent to <code>while true</code>.</p>
<p>When using a JavaScript loop to generate functions, its common to insert a closure wrapper in order to ensure that loop variables are closed over, and all the generated functions dont just share the final values. CoffeeScript provides the <code>do</code> keyword, which immediately invokes a passed function, forwarding any arguments.</p>
<aside class="code-example container-fluid bg-ribbed-dark" data-example="do">
<div class="row">
<div class="col-md-6 coffeescript-input-column">
<textarea class="coffeescript-input" id="do-coffee">for filename in list
do (filename) ->
if filename not in ['.DS_Store', 'Thumbs.db', 'ehthumbs.db']
fs.readFile filename, (err, contents) ->
compile filename, contents.toString()
</textarea>
<pre class="placeholder-code"><span class="cm-keyword">for</span> <span class="cm-variable">filename</span> <span class="cm-operator">in</span> <span class="cm-variable">list</span>
<span class="cm-keyword">do</span> <span class="cm-punctuation">(</span><span class="cm-variable">filename</span><span class="cm-punctuation">)</span> <span class="cm-operator">-></span>
<span class="cm-keyword">if</span> <span class="cm-variable">filename</span> <span class="cm-operator">not</span> <span class="cm-operator">in</span> <span class="cm-punctuation">[</span><span class="cm-string">'.DS_Store'</span><span class="cm-punctuation">,</span> <span class="cm-string">'Thumbs.db'</span><span class="cm-punctuation">,</span> <span class="cm-string">'ehthumbs.db'</span><span class="cm-punctuation">]</span>
<span class="cm-variable">fs</span><span class="cm-punctuation">.</span><span class="cm-property">readFile</span> <span class="cm-variable">filename</span><span class="cm-punctuation">,</span> <span class="cm-punctuation">(</span><span class="cm-variable">err</span><span class="cm-punctuation">,</span> <span class="cm-variable">contents</span><span class="cm-punctuation">)</span> <span class="cm-operator">-></span>
<span class="cm-variable">compile</span> <span class="cm-variable">filename</span><span class="cm-punctuation">,</span> <span class="cm-variable">contents</span><span class="cm-punctuation">.</span><span class="cm-property">toString</span><span class="cm-punctuation">()</span>
</pre>
</div>
<div class="col-md-6 javascript-output-column">
<textarea class="javascript-output" id="do-js">var filename, i, len;
for (i = 0, len = list.length; i < len; i++) {
filename = list[i];
(function(filename) {
if (filename !== '.DS_Store' && filename !== 'Thumbs.db' && filename !== 'ehthumbs.db') {
return fs.readFile(filename, function(err, contents) {
return compile(filename, contents.toString());
});
}
})(filename);
}
</textarea>
<pre class="placeholder-code"><span class="cm-keyword">var</span> <span class="cm-def">filename</span>, <span class="cm-def">i</span>, <span class="cm-def">len</span>;
<span class="cm-keyword">for</span> (<span class="cm-variable">i</span> <span class="cm-operator">=</span> <span class="cm-number">0</span>, <span class="cm-variable">len</span> <span class="cm-operator">=</span> <span class="cm-variable">list</span>.<span class="cm-property">length</span>; <span class="cm-variable">i</span> <span class="cm-operator">&lt;</span> <span class="cm-variable">len</span>; <span class="cm-variable">i</span><span class="cm-operator">++</span>) {
<span class="cm-variable">filename</span> <span class="cm-operator">=</span> <span class="cm-variable">list</span>[<span class="cm-variable">i</span>];
(<span class="cm-keyword">function</span>(<span class="cm-def">filename</span>) {
<span class="cm-keyword">if</span> (<span class="cm-variable-2">filename</span> <span class="cm-operator">!==</span> <span class="cm-string">'.DS_Store'</span> <span class="cm-operator">&amp;&amp;</span> <span class="cm-variable-2">filename</span> <span class="cm-operator">!==</span> <span class="cm-string">'Thumbs.db'</span> <span class="cm-operator">&amp;&amp;</span> <span class="cm-variable-2">filename</span> <span class="cm-operator">!==</span> <span class="cm-string">'ehthumbs.db'</span>) {
<span class="cm-keyword">return</span> <span class="cm-variable">fs</span>.<span class="cm-property">readFile</span>(<span class="cm-variable-2">filename</span>, <span class="cm-keyword">function</span>(<span class="cm-def">err</span>, <span class="cm-def">contents</span>) {
<span class="cm-keyword">return</span> <span class="cm-variable">compile</span>(<span class="cm-variable-2">filename</span>, <span class="cm-variable-2">contents</span>.<span class="cm-property">toString</span>());
});
}
})(<span class="cm-variable">filename</span>);
}
</pre>
</div>
</div>
</aside>
</section>
<section id="slices">
<h2>Array Slicing and Splicing with Ranges</h2>
<p>Ranges can also be used to extract slices of arrays. With two dots (<code>3..6</code>), the range is inclusive (<code>3, 4, 5, 6</code>); with three dots (<code>3...6</code>), the range excludes the end (<code>3, 4, 5</code>). Slices indices have useful defaults. An omitted first index defaults to zero and an omitted second index defaults to the size of the array.</p>
<aside class="code-example container-fluid bg-ribbed-dark" data-example="slices">
<div class="row">
<div class="col-md-6 coffeescript-input-column">
<textarea class="coffeescript-input" id="slices-coffee">numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
start = numbers[0..2]
middle = numbers[3...-2]
end = numbers[-2..]
copy = numbers[..]
</textarea>
<pre class="placeholder-code"><span class="cm-variable">numbers</span> <span class="cm-punctuation">=</span> <span class="cm-punctuation">[</span><span class="cm-number">1</span><span class="cm-punctuation">,</span> <span class="cm-number">2</span><span class="cm-punctuation">,</span> <span class="cm-number">3</span><span class="cm-punctuation">,</span> <span class="cm-number">4</span><span class="cm-punctuation">,</span> <span class="cm-number">5</span><span class="cm-punctuation">,</span> <span class="cm-number">6</span><span class="cm-punctuation">,</span> <span class="cm-number">7</span><span class="cm-punctuation">,</span> <span class="cm-number">8</span><span class="cm-punctuation">,</span> <span class="cm-number">9</span><span class="cm-punctuation">]</span>
<span class="cm-variable">start</span> <span class="cm-punctuation">=</span> <span class="cm-variable">numbers</span><span class="cm-punctuation">[</span><span class="cm-number">0..2</span><span class="cm-punctuation">]</span>
<span class="cm-variable">middle</span> <span class="cm-punctuation">=</span> <span class="cm-variable">numbers</span><span class="cm-punctuation">[</span><span class="cm-number">3</span><span class="cm-punctuation">...</span><span class="cm-number">-2</span><span class="cm-punctuation">]</span>
<span class="cm-variable">end</span> <span class="cm-punctuation">=</span> <span class="cm-variable">numbers</span><span class="cm-punctuation">[</span><span class="cm-number">-2</span><span class="cm-punctuation">..]</span>
<span class="cm-variable">copy</span> <span class="cm-punctuation">=</span> <span class="cm-variable">numbers</span><span class="cm-punctuation">[..]</span>
</pre>
</div>
<div class="col-md-6 javascript-output-column">
<textarea class="javascript-output" id="slices-js">var copy, end, middle, numbers, start;
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];
start = numbers.slice(0, 3);
middle = numbers.slice(3, -2);
end = numbers.slice(-2);
copy = numbers.slice(0);
</textarea>
<pre class="placeholder-code"><span class="cm-keyword">var</span> <span class="cm-def">copy</span>, <span class="cm-def">end</span>, <span class="cm-def">middle</span>, <span class="cm-def">numbers</span>, <span class="cm-def">start</span>;
<span class="cm-variable">numbers</span> <span class="cm-operator">=</span> [<span class="cm-number">1</span>, <span class="cm-number">2</span>, <span class="cm-number">3</span>, <span class="cm-number">4</span>, <span class="cm-number">5</span>, <span class="cm-number">6</span>, <span class="cm-number">7</span>, <span class="cm-number">8</span>, <span class="cm-number">9</span>];
<span class="cm-variable">start</span> <span class="cm-operator">=</span> <span class="cm-variable">numbers</span>.<span class="cm-property">slice</span>(<span class="cm-number">0</span>, <span class="cm-number">3</span>);
<span class="cm-variable">middle</span> <span class="cm-operator">=</span> <span class="cm-variable">numbers</span>.<span class="cm-property">slice</span>(<span class="cm-number">3</span>, <span class="cm-operator">-</span><span class="cm-number">2</span>);
<span class="cm-variable">end</span> <span class="cm-operator">=</span> <span class="cm-variable">numbers</span>.<span class="cm-property">slice</span>(<span class="cm-operator">-</span><span class="cm-number">2</span>);
<span class="cm-variable">copy</span> <span class="cm-operator">=</span> <span class="cm-variable">numbers</span>.<span class="cm-property">slice</span>(<span class="cm-number">0</span>);
</pre>
</div>
</div>
<div class="row">
<div class="col text-right">
<button type="button" class="btn btn-primary" data-action="run-code-example" data-example="slices" data-run="middle"><small><svg class="play-button" viewBox="0 0 24 24">
<path d="M2.56-0.01v24.02L21.44 11.98 2.56-0.01z"></path>
</svg>
</small>middle</button>
</div>
</div>
</aside>
<p>The same syntax can be used with assignment to replace a segment of an array with new values, splicing it.</p>
<aside class="code-example container-fluid bg-ribbed-dark" data-example="splices">
<div class="row">
<div class="col-md-6 coffeescript-input-column">
<textarea class="coffeescript-input" id="splices-coffee">numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
numbers[3..6] = [-3, -4, -5, -6]
</textarea>
<pre class="placeholder-code"><span class="cm-variable">numbers</span> <span class="cm-punctuation">=</span> <span class="cm-punctuation">[</span><span class="cm-number">0</span><span class="cm-punctuation">,</span> <span class="cm-number">1</span><span class="cm-punctuation">,</span> <span class="cm-number">2</span><span class="cm-punctuation">,</span> <span class="cm-number">3</span><span class="cm-punctuation">,</span> <span class="cm-number">4</span><span class="cm-punctuation">,</span> <span class="cm-number">5</span><span class="cm-punctuation">,</span> <span class="cm-number">6</span><span class="cm-punctuation">,</span> <span class="cm-number">7</span><span class="cm-punctuation">,</span> <span class="cm-number">8</span><span class="cm-punctuation">,</span> <span class="cm-number">9</span><span class="cm-punctuation">]</span>
<span class="cm-variable">numbers</span><span class="cm-punctuation">[</span><span class="cm-number">3..6</span><span class="cm-punctuation">]</span> <span class="cm-punctuation">=</span> <span class="cm-punctuation">[</span><span class="cm-number">-3</span><span class="cm-punctuation">,</span> <span class="cm-number">-4</span><span class="cm-punctuation">,</span> <span class="cm-number">-5</span><span class="cm-punctuation">,</span> <span class="cm-number">-6</span><span class="cm-punctuation">]</span>
</pre>
</div>
<div class="col-md-6 javascript-output-column">
<textarea class="javascript-output" id="splices-js">var numbers, ref,
splice = [].splice;
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
splice.apply(numbers, [3, 4].concat(ref = [-3, -4, -5, -6])), ref;
</textarea>
<pre class="placeholder-code"><span class="cm-keyword">var</span> <span class="cm-def">numbers</span>, <span class="cm-def">ref</span>,
<span class="cm-def">splice</span> <span class="cm-operator">=</span> [].<span class="cm-property">splice</span>;
<span class="cm-variable">numbers</span> <span class="cm-operator">=</span> [<span class="cm-number">0</span>, <span class="cm-number">1</span>, <span class="cm-number">2</span>, <span class="cm-number">3</span>, <span class="cm-number">4</span>, <span class="cm-number">5</span>, <span class="cm-number">6</span>, <span class="cm-number">7</span>, <span class="cm-number">8</span>, <span class="cm-number">9</span>];
<span class="cm-variable">splice</span>.<span class="cm-property">apply</span>(<span class="cm-variable">numbers</span>, [<span class="cm-number">3</span>, <span class="cm-number">4</span>].<span class="cm-property">concat</span>(<span class="cm-variable">ref</span> <span class="cm-operator">=</span> [<span class="cm-operator">-</span><span class="cm-number">3</span>, <span class="cm-operator">-</span><span class="cm-number">4</span>, <span class="cm-operator">-</span><span class="cm-number">5</span>, <span class="cm-operator">-</span><span class="cm-number">6</span>])), <span class="cm-variable">ref</span>;
</pre>
</div>
</div>
<div class="row">
<div class="col text-right">
<button type="button" class="btn btn-primary" data-action="run-code-example" data-example="splices" data-run="numbers"><small><svg class="play-button" viewBox="0 0 24 24">
<path d="M2.56-0.01v24.02L21.44 11.98 2.56-0.01z"></path>
</svg>
</small>numbers</button>
</div>
</div>
</aside>
<p>Note that JavaScript strings are immutable, and cant be spliced.</p>
</section>
<section id="expressions">
<h2>Everything is an Expression (at least, as much as possible)</h2>
<p>You might have noticed how even though we dont add return statements to CoffeeScript functions, they nonetheless return their final value. The CoffeeScript compiler tries to make sure that all statements in the language can be used as expressions. Watch how the <code>return</code> gets pushed down into each possible branch of execution in the function below.</p>
<aside class="code-example container-fluid bg-ribbed-dark" data-example="expressions">
<div class="row">
<div class="col-md-6 coffeescript-input-column">
<textarea class="coffeescript-input" id="expressions-coffee">grade = (student) ->
if student.excellentWork
"A+"
else if student.okayStuff
if student.triedHard then "B" else "B-"
else
"C"
eldest = if 24 > 21 then "Liz" else "Ike"
</textarea>
<pre class="placeholder-code"><span class="cm-variable">grade</span> <span class="cm-punctuation">=</span> <span class="cm-punctuation">(</span><span class="cm-variable">student</span><span class="cm-punctuation">)</span> <span class="cm-operator">-></span>
<span class="cm-keyword">if</span> <span class="cm-variable">student</span><span class="cm-punctuation">.</span><span class="cm-property">excellentWork</span>
<span class="cm-string">"A+"</span>
<span class="cm-dedent"> </span><span class="cm-keyword">else</span> <span class="cm-keyword">if</span> <span class="cm-variable">student</span><span class="cm-punctuation">.</span><span class="cm-property">okayStuff</span>
<span class="cm-dedent"> </span><span class="cm-keyword">if</span> <span class="cm-variable">student</span><span class="cm-punctuation">.</span><span class="cm-property">triedHard</span> <span class="cm-keyword">then</span> <span class="cm-string">"B"</span> <span class="cm-keyword">else</span> <span class="cm-string">"B-"</span>
<span class="cm-dedent"> </span><span class="cm-keyword">else</span>
<span class="cm-string">"C"</span>
<span class="cm-variable">eldest</span> <span class="cm-punctuation">=</span> <span class="cm-keyword">if</span> <span class="cm-number">24</span> <span class="cm-operator">></span> <span class="cm-number">21</span> <span class="cm-keyword">then</span> <span class="cm-string">"Liz"</span> <span class="cm-keyword">else</span> <span class="cm-string">"Ike"</span>
</pre>
</div>
<div class="col-md-6 javascript-output-column">
<textarea class="javascript-output" id="expressions-js">var eldest, grade;
grade = function(student) {
if (student.excellentWork) {
return "A+";
} else if (student.okayStuff) {
if (student.triedHard) {
return "B";
} else {
return "B-";
}
} else {
return "C";
}
};
eldest = 24 > 21 ? "Liz" : "Ike";
</textarea>
<pre class="placeholder-code"><span class="cm-keyword">var</span> <span class="cm-def">eldest</span>, <span class="cm-def">grade</span>;
<span class="cm-variable">grade</span> <span class="cm-operator">=</span> <span class="cm-keyword">function</span>(<span class="cm-def">student</span>) {
<span class="cm-keyword">if</span> (<span class="cm-variable-2">student</span>.<span class="cm-property">excellentWork</span>) {
<span class="cm-keyword">return</span> <span class="cm-string">"A+"</span>;
} <span class="cm-keyword">else</span> <span class="cm-keyword">if</span> (<span class="cm-variable-2">student</span>.<span class="cm-property">okayStuff</span>) {
<span class="cm-keyword">if</span> (<span class="cm-variable-2">student</span>.<span class="cm-property">triedHard</span>) {
<span class="cm-keyword">return</span> <span class="cm-string">"B"</span>;
} <span class="cm-keyword">else</span> {
<span class="cm-keyword">return</span> <span class="cm-string">"B-"</span>;
}
} <span class="cm-keyword">else</span> {
<span class="cm-keyword">return</span> <span class="cm-string">"C"</span>;
}
};
<span class="cm-variable">eldest</span> <span class="cm-operator">=</span> <span class="cm-number">24</span> <span class="cm-operator">></span> <span class="cm-number">21</span> <span class="cm-operator">?</span> <span class="cm-string">"Liz"</span> : <span class="cm-string">"Ike"</span>;
</pre>
</div>
</div>
<div class="row">
<div class="col text-right">
<button type="button" class="btn btn-primary" data-action="run-code-example" data-example="expressions" data-run="eldest"><small><svg class="play-button" viewBox="0 0 24 24">
<path d="M2.56-0.01v24.02L21.44 11.98 2.56-0.01z"></path>
</svg>
</small>eldest</button>
</div>
</div>
</aside>
<p>Even though functions will always return their final value, its both possible and encouraged to return early from a function body writing out the explicit return (<code>return value</code>), when you know that youre done.</p>
<p>Because variable declarations occur at the top of scope, assignment can be used within expressions, even for variables that havent been seen before:</p>
<aside class="code-example container-fluid bg-ribbed-dark" data-example="expressions_assignment">
<div class="row">
<div class="col-md-6 coffeescript-input-column">
<textarea class="coffeescript-input" id="expressions_assignment-coffee">six = (one = 1) + (two = 2) + (three = 3)
</textarea>
<pre class="placeholder-code"><span class="cm-variable">six</span> <span class="cm-punctuation">=</span> <span class="cm-punctuation">(</span><span class="cm-variable">one</span> <span class="cm-punctuation">=</span> <span class="cm-number">1</span><span class="cm-punctuation">)</span> <span class="cm-operator">+</span> <span class="cm-punctuation">(</span><span class="cm-variable">two</span> <span class="cm-punctuation">=</span> <span class="cm-number">2</span><span class="cm-punctuation">)</span> <span class="cm-operator">+</span> <span class="cm-punctuation">(</span><span class="cm-variable">three</span> <span class="cm-punctuation">=</span> <span class="cm-number">3</span><span class="cm-punctuation">)</span>
</pre>
</div>
<div class="col-md-6 javascript-output-column">
<textarea class="javascript-output" id="expressions_assignment-js">var one, six, three, two;
six = (one = 1) + (two = 2) + (three = 3);
</textarea>
<pre class="placeholder-code"><span class="cm-keyword">var</span> <span class="cm-def">one</span>, <span class="cm-def">six</span>, <span class="cm-def">three</span>, <span class="cm-def">two</span>;
<span class="cm-variable">six</span> <span class="cm-operator">=</span> (<span class="cm-variable">one</span> <span class="cm-operator">=</span> <span class="cm-number">1</span>) <span class="cm-operator">+</span> (<span class="cm-variable">two</span> <span class="cm-operator">=</span> <span class="cm-number">2</span>) <span class="cm-operator">+</span> (<span class="cm-variable">three</span> <span class="cm-operator">=</span> <span class="cm-number">3</span>);
</pre>
</div>
</div>
<div class="row">
<div class="col text-right">
<button type="button" class="btn btn-primary" data-action="run-code-example" data-example="expressions_assignment" data-run="six"><small><svg class="play-button" viewBox="0 0 24 24">
<path d="M2.56-0.01v24.02L21.44 11.98 2.56-0.01z"></path>
</svg>
</small>six</button>
</div>
</div>
</aside>
<p>Things that would otherwise be statements in JavaScript, when used as part of an expression in CoffeeScript, are converted into expressions by wrapping them in a closure. This lets you do useful things, like assign the result of a comprehension to a variable:</p>
<aside class="code-example container-fluid bg-ribbed-dark" data-example="expressions_comprehension">
<div class="row">
<div class="col-md-6 coffeescript-input-column">
<textarea class="coffeescript-input" id="expressions_comprehension-coffee"># The first ten global properties.
globals = (name for name of window)[0...10]
</textarea>
<pre class="placeholder-code"><span class="cm-comment"># The first ten global properties.</span>
<span class="cm-variable">globals</span> <span class="cm-punctuation">=</span> <span class="cm-punctuation">(</span><span class="cm-variable">name</span> <span class="cm-keyword">for</span> <span class="cm-variable">name</span> <span class="cm-keyword">of</span> <span class="cm-variable">window</span><span class="cm-punctuation">)[</span><span class="cm-number">0</span><span class="cm-punctuation">...</span><span class="cm-number">10</span><span class="cm-punctuation">]</span>
</pre>
</div>
<div class="col-md-6 javascript-output-column">
<textarea class="javascript-output" id="expressions_comprehension-js">// The first ten global properties.
var globals, name;
globals = ((function() {
var results;
results = [];
for (name in window) {
results.push(name);
}
return results;
})()).slice(0, 10);
</textarea>
<pre class="placeholder-code"><span class="cm-comment">// The first ten global properties.</span>
<span class="cm-keyword">var</span> <span class="cm-def">globals</span>, <span class="cm-def">name</span>;
<span class="cm-variable">globals</span> <span class="cm-operator">=</span> ((<span class="cm-keyword">function</span>() {
<span class="cm-keyword">var</span> <span class="cm-def">results</span>;
<span class="cm-variable-2">results</span> <span class="cm-operator">=</span> [];
<span class="cm-keyword">for</span> (<span class="cm-variable">name</span> <span class="cm-keyword">in</span> <span class="cm-variable">window</span>) {
<span class="cm-variable-2">results</span>.<span class="cm-property">push</span>(<span class="cm-variable">name</span>);
}
<span class="cm-keyword">return</span> <span class="cm-variable-2">results</span>;
})()).<span class="cm-property">slice</span>(<span class="cm-number">0</span>, <span class="cm-number">10</span>);
</pre>
</div>
</div>
<div class="row">
<div class="col text-right">
<button type="button" class="btn btn-primary" data-action="run-code-example" data-example="expressions_comprehension" data-run="globals"><small><svg class="play-button" viewBox="0 0 24 24">
<path d="M2.56-0.01v24.02L21.44 11.98 2.56-0.01z"></path>
</svg>
</small>globals</button>
</div>
</div>
</aside>
<p>As well as silly things, like passing a <code>try</code>/<code>catch</code> statement directly into a function call:</p>
<aside class="code-example container-fluid bg-ribbed-dark" data-example="expressions_try">
<div class="row">
<div class="col-md-6 coffeescript-input-column">
<textarea class="coffeescript-input" id="expressions_try-coffee">alert(
try
nonexistent / undefined
catch error
"And the error is ... #{error}"
)
</textarea>
<pre class="placeholder-code"><span class="cm-variable">alert</span><span class="cm-punctuation">(</span>
<span class="cm-keyword">try</span>
<span class="cm-indent"> </span><span class="cm-variable">nonexistent</span> <span class="cm-operator">/</span> <span class="cm-atom">undefined</span>
<span class="cm-dedent"> </span><span class="cm-keyword">catch</span> <span class="cm-variable">error</span>
<span class="cm-string">"And the error is ... #{error}"</span>
<span class="cm-punctuation">)</span>
</pre>
</div>
<div class="col-md-6 javascript-output-column">
<textarea class="javascript-output" id="expressions_try-js">var error;
alert((function() {
try {
return nonexistent / void 0;
} catch (error1) {
error = error1;
return `And the error is ... ${error}`;
}
})());
</textarea>
<pre class="placeholder-code"><span class="cm-keyword">var</span> <span class="cm-def">error</span>;
<span class="cm-variable">alert</span>((<span class="cm-keyword">function</span>() {
<span class="cm-keyword">try</span> {
<span class="cm-keyword">return</span> <span class="cm-variable">nonexistent</span> <span class="cm-operator">/</span> <span class="cm-keyword">void</span> <span class="cm-number">0</span>;
} <span class="cm-keyword">catch</span> (<span class="cm-def">error1</span>) {
<span class="cm-variable">error</span> <span class="cm-operator">=</span> <span class="cm-variable-2">error1</span>;
<span class="cm-keyword">return</span> <span class="cm-string-2">`And the error is ... ${</span><span class="cm-variable">error</span><span class="cm-string-2">}`</span>;
}
})());
</pre>
</div>
</div>
<div class="row">
<div class="col text-right">
<button type="button" class="btn btn-primary" data-action="run-code-example" data-example="expressions_try" data-run="true"><small><svg class="play-button" viewBox="0 0 24 24">
<path d="M2.56-0.01v24.02L21.44 11.98 2.56-0.01z"></path>
</svg>
</small></button>
</div>
</div>
</aside>
<p>There are a handful of statements in JavaScript that cant be meaningfully converted into expressions, namely <code>break</code>, <code>continue</code>, and <code>return</code>. If you make use of them within a block of code, CoffeeScript wont try to perform the conversion.</p>
</section>
<section id="operators">
<h2>Operators and Aliases</h2>
<p>Because the <code>==</code> operator frequently causes undesirable coercion, is intransitive, and has a different meaning than in other languages, CoffeeScript compiles <code>==</code> into <code>===</code>, and <code>!=</code> into <code>!==</code>. In addition, <code>is</code> compiles into <code>===</code>, and <code>isnt</code> into <code>!==</code>.</p>
<p>You can use <code>not</code> as an alias for <code>!</code>.</p>
<p>For logic, <code>and</code> compiles to <code>&amp;&amp;</code>, and <code>or</code> into <code>||</code>.</p>
<p>Instead of a newline or semicolon, <code>then</code> can be used to separate conditions from expressions, in <code>while</code>, <code>if</code>/<code>else</code>, and <code>switch</code>/<code>when</code> statements.</p>
<p>As in <a href="http://yaml.org/">YAML</a>, <code>on</code> and <code>yes</code> are the same as boolean <code>true</code>, while <code>off</code> and <code>no</code> are boolean <code>false</code>.</p>
<p><code>unless</code> can be used as the inverse of <code>if</code>.</p>
<p>As a shortcut for <code>this.property</code>, you can use <code>@property</code>.</p>
<p>You can use <code>in</code> to test for array presence, and <code>of</code> to test for JavaScript object-key presence.</p>
<p>In a <code>for</code> loop, <code>from</code> compiles to the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of">ES2015 <code>of</code></a>. (Yes, its unfortunate; the CoffeeScript <code>of</code> predates the ES2015 <code>of</code>.)</p>
<p>To simplify math expressions, <code>**</code> can be used for exponentiation and <code>//</code> performs floor division. <code>%</code> works just like in JavaScript, while <code>%%</code> provides <a href="https://en.wikipedia.org/wiki/Modulo_operation">“dividend dependent modulo”</a>:</p>
<aside class="code-example container-fluid bg-ribbed-dark" data-example="modulo">
<div class="row">
<div class="col-md-6 coffeescript-input-column">
<textarea class="coffeescript-input" id="modulo-coffee">-7 % 5 == -2 # The remainder of 7 / 5
-7 %% 5 == 3 # n %% 5 is always between 0 and 4
tabs.selectTabAtIndex((tabs.currentIndex - count) %% tabs.length)
</textarea>
<pre class="placeholder-code"><span class="cm-number">-7</span> <span class="cm-operator">%</span> <span class="cm-number">5</span> <span class="cm-operator">==</span> <span class="cm-number">-2</span> <span class="cm-comment"># The remainder of 7 / 5</span>
<span class="cm-number">-7</span> <span class="cm-operator">%%</span> <span class="cm-number">5</span> <span class="cm-operator">==</span> <span class="cm-number">3</span> <span class="cm-comment"># n %% 5 is always between 0 and 4</span>
<span class="cm-variable">tabs</span><span class="cm-punctuation">.</span><span class="cm-property">selectTabAtIndex</span><span class="cm-punctuation">((</span><span class="cm-variable">tabs</span><span class="cm-punctuation">.</span><span class="cm-property">currentIndex</span> <span class="cm-operator">-</span> <span class="cm-variable">count</span><span class="cm-punctuation">)</span> <span class="cm-operator">%%</span> <span class="cm-variable">tabs</span><span class="cm-punctuation">.</span><span class="cm-property">length</span><span class="cm-punctuation">)</span>
</pre>
</div>
<div class="col-md-6 javascript-output-column">
<textarea class="javascript-output" id="modulo-js">var modulo = function(a, b) { return (+a % (b = +b) + b) % b; };
-7 % 5 === -2; // The remainder of 7 / 5
modulo(-7, 5) === 3; // n %% 5 is always between 0 and 4
tabs.selectTabAtIndex(modulo(tabs.currentIndex - count, tabs.length));
</textarea>
<pre class="placeholder-code"><span class="cm-keyword">var</span> <span class="cm-def">modulo</span> <span class="cm-operator">=</span> <span class="cm-keyword">function</span>(<span class="cm-def">a</span>, <span class="cm-def">b</span>) { <span class="cm-keyword">return</span> (<span class="cm-operator">+</span><span class="cm-variable-2">a</span> <span class="cm-operator">%</span> (<span class="cm-variable-2">b</span> <span class="cm-operator">=</span> <span class="cm-operator">+</span><span class="cm-variable-2">b</span>) <span class="cm-operator">+</span> <span class="cm-variable-2">b</span>) <span class="cm-operator">%</span> <span class="cm-variable-2">b</span>; };
<span class="cm-operator">-</span><span class="cm-number">7</span> <span class="cm-operator">%</span> <span class="cm-number">5</span> <span class="cm-operator">===</span> <span class="cm-operator">-</span><span class="cm-number">2</span>; <span class="cm-comment">// The remainder of 7 / 5</span>
<span class="cm-variable">modulo</span>(<span class="cm-operator">-</span><span class="cm-number">7</span>, <span class="cm-number">5</span>) <span class="cm-operator">===</span> <span class="cm-number">3</span>; <span class="cm-comment">// n %% 5 is always between 0 and 4</span>
<span class="cm-variable">tabs</span>.<span class="cm-property">selectTabAtIndex</span>(<span class="cm-variable">modulo</span>(<span class="cm-variable">tabs</span>.<span class="cm-property">currentIndex</span> <span class="cm-operator">-</span> <span class="cm-variable">count</span>, <span class="cm-variable">tabs</span>.<span class="cm-property">length</span>));
</pre>
</div>
</div>
</aside>
<p>All together now:</p>
<table>
<thead>
<tr>
<th>CoffeeScript</th>
<th>JavaScript</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>is</code></td>
<td><code>===</code></td>
</tr>
<tr>
<td><code>isnt</code></td>
<td><code>!==</code></td>
</tr>
<tr>
<td><code>not</code></td>
<td><code>!</code></td>
</tr>
<tr>
<td><code>and</code></td>
<td><code>&amp;&amp;</code></td>
</tr>
<tr>
<td><code>or</code></td>
<td><code>||</code></td>
</tr>
<tr>
<td><code>true</code>, <code>yes</code>, <code>on</code></td>
<td><code>true</code></td>
</tr>
<tr>
<td><code>false</code>, <code>no</code>, <code>off</code></td>
<td><code>false</code></td>
</tr>
<tr>
<td><code>@</code>, <code>this</code></td>
<td><code>this</code></td>
</tr>
<tr>
<td><code>a in b</code></td>
<td><code>[].indexOf.call(b, a) &gt;= 0</code></td>
</tr>
<tr>
<td><code>a of b</code></td>
<td><code>a in b</code></td>
</tr>
<tr>
<td><code>for a from b</code></td>
<td><code>for (a of b)</code></td>
</tr>
<tr>
<td><code>a ** b</code></td>
<td><code>a ** b</code></td>
</tr>
<tr>
<td><code>a // b</code></td>
<td><code>Math.floor(a / b)</code></td>
</tr>
<tr>
<td><code>a %% b</code></td>
<td><code>(a % b + b) % b</code></td>
</tr>
</tbody>
</table>
<aside class="code-example container-fluid bg-ribbed-dark" data-example="aliases">
<div class="row">
<div class="col-md-6 coffeescript-input-column">
<textarea class="coffeescript-input" id="aliases-coffee">launch() if ignition is on
volume = 10 if band isnt SpinalTap
letTheWildRumpusBegin() unless answer is no
if car.speed < limit then accelerate()
winner = yes if pick in [47, 92, 13]
print inspect "My name is #{@name}"
</textarea>
<pre class="placeholder-code"><span class="cm-variable">launch</span><span class="cm-punctuation">()</span> <span class="cm-keyword">if</span> <span class="cm-variable">ignition</span> <span class="cm-operator">is</span> <span class="cm-atom">on</span>
<span class="cm-variable">volume</span> <span class="cm-punctuation">=</span> <span class="cm-number">10</span> <span class="cm-keyword">if</span> <span class="cm-variable">band</span> <span class="cm-operator">isnt</span> <span class="cm-variable">SpinalTap</span>
<span class="cm-variable">letTheWildRumpusBegin</span><span class="cm-punctuation">()</span> <span class="cm-keyword">unless</span> <span class="cm-variable">answer</span> <span class="cm-operator">is</span> <span class="cm-atom">no</span>
<span class="cm-keyword">if</span> <span class="cm-variable">car</span><span class="cm-punctuation">.</span><span class="cm-property">speed</span> <span class="cm-operator">&lt;</span> <span class="cm-variable">limit</span> <span class="cm-keyword">then</span> <span class="cm-variable">accelerate</span><span class="cm-punctuation">()</span>
<span class="cm-variable">winner</span> <span class="cm-punctuation">=</span> <span class="cm-atom">yes</span> <span class="cm-keyword">if</span> <span class="cm-variable">pick</span> <span class="cm-operator">in</span> <span class="cm-punctuation">[</span><span class="cm-number">47</span><span class="cm-punctuation">,</span> <span class="cm-number">92</span><span class="cm-punctuation">,</span> <span class="cm-number">13</span><span class="cm-punctuation">]</span>
<span class="cm-variable">print</span> <span class="cm-variable">inspect</span> <span class="cm-string">"My name is #{@name}"</span>
</pre>
</div>
<div class="col-md-6 javascript-output-column">
<textarea class="javascript-output" id="aliases-js">var volume, winner;
if (ignition === true) {
launch();
}
if (band !== SpinalTap) {
volume = 10;
}
if (answer !== false) {
letTheWildRumpusBegin();
}
if (car.speed < limit) {
accelerate();
}
if (pick === 47 || pick === 92 || pick === 13) {
winner = true;
}
print(inspect(`My name is ${this.name}`));
</textarea>
<pre class="placeholder-code"><span class="cm-keyword">var</span> <span class="cm-def">volume</span>, <span class="cm-def">winner</span>;
<span class="cm-keyword">if</span> (<span class="cm-variable">ignition</span> <span class="cm-operator">===</span> <span class="cm-atom">true</span>) {
<span class="cm-variable">launch</span>();
}
<span class="cm-keyword">if</span> (<span class="cm-variable">band</span> <span class="cm-operator">!==</span> <span class="cm-variable">SpinalTap</span>) {
<span class="cm-variable">volume</span> <span class="cm-operator">=</span> <span class="cm-number">10</span>;
}
<span class="cm-keyword">if</span> (<span class="cm-variable">answer</span> <span class="cm-operator">!==</span> <span class="cm-atom">false</span>) {
<span class="cm-variable">letTheWildRumpusBegin</span>();
}
<span class="cm-keyword">if</span> (<span class="cm-variable">car</span>.<span class="cm-property">speed</span> <span class="cm-operator">&lt;</span> <span class="cm-variable">limit</span>) {
<span class="cm-variable">accelerate</span>();
}
<span class="cm-keyword">if</span> (<span class="cm-variable">pick</span> <span class="cm-operator">===</span> <span class="cm-number">47</span> <span class="cm-operator">||</span> <span class="cm-variable">pick</span> <span class="cm-operator">===</span> <span class="cm-number">92</span> <span class="cm-operator">||</span> <span class="cm-variable">pick</span> <span class="cm-operator">===</span> <span class="cm-number">13</span>) {
<span class="cm-variable">winner</span> <span class="cm-operator">=</span> <span class="cm-atom">true</span>;
}
<span class="cm-variable">print</span>(<span class="cm-variable">inspect</span>(<span class="cm-string-2">`My name is ${</span><span class="cm-keyword">this</span>.<span class="cm-property">name</span><span class="cm-string-2">}`</span>));
</pre>
</div>
</div>
</aside>
</section>
<section id="existential-operator">
<h2>The Existential Operator</h2>
<p>Its a little difficult to check for the existence of a variable in JavaScript. <code>if (variable) …</code> comes close, but fails for zero, the empty string, and false (to name just the most common cases). CoffeeScripts existential operator <code>?</code> returns true unless a variable is <code>null</code> or <code>undefined</code> or undeclared, which makes it analogous to Rubys <code>nil?</code>.</p>
<p>It can also be used for safer conditional assignment than the JavaScript pattern <code>a = a || value</code> provides, for cases where you may be handling numbers or strings.</p>
<aside class="code-example container-fluid bg-ribbed-dark" data-example="existence">
<div class="row">
<div class="col-md-6 coffeescript-input-column">
<textarea class="coffeescript-input" id="existence-coffee">solipsism = true if mind? and not world?
speed = 0
speed ?= 15
footprints = yeti ? "bear"
</textarea>
<pre class="placeholder-code"><span class="cm-variable">solipsism</span> <span class="cm-punctuation">=</span> <span class="cm-atom">true</span> <span class="cm-keyword">if</span> <span class="cm-variable">mind</span><span class="cm-operator">?</span> <span class="cm-operator">and</span> <span class="cm-operator">not</span> <span class="cm-variable">world</span><span class="cm-operator">?</span>
<span class="cm-variable">speed</span> <span class="cm-punctuation">=</span> <span class="cm-number">0</span>
<span class="cm-variable">speed</span> <span class="cm-operator">?</span><span class="cm-punctuation">=</span> <span class="cm-number">15</span>
<span class="cm-variable">footprints</span> <span class="cm-punctuation">=</span> <span class="cm-variable">yeti</span> <span class="cm-operator">?</span> <span class="cm-string">"bear"</span>
</pre>
</div>
<div class="col-md-6 javascript-output-column">
<textarea class="javascript-output" id="existence-js">var footprints, solipsism, speed;
if ((typeof mind !== "undefined" && mind !== null) && (typeof world === "undefined" || world === null)) {
solipsism = true;
}
speed = 0;
if (speed == null) {
speed = 15;
}
footprints = typeof yeti !== "undefined" && yeti !== null ? yeti : "bear";
</textarea>
<pre class="placeholder-code"><span class="cm-keyword">var</span> <span class="cm-def">footprints</span>, <span class="cm-def">solipsism</span>, <span class="cm-def">speed</span>;
<span class="cm-keyword">if</span> ((<span class="cm-keyword">typeof</span> <span class="cm-variable">mind</span> <span class="cm-operator">!==</span> <span class="cm-string">"undefined"</span> <span class="cm-operator">&amp;&amp;</span> <span class="cm-variable">mind</span> <span class="cm-operator">!==</span> <span class="cm-atom">null</span>) <span class="cm-operator">&amp;&amp;</span> (<span class="cm-keyword">typeof</span> <span class="cm-variable">world</span> <span class="cm-operator">===</span> <span class="cm-string">"undefined"</span> <span class="cm-operator">||</span> <span class="cm-variable">world</span> <span class="cm-operator">===</span> <span class="cm-atom">null</span>)) {
<span class="cm-variable">solipsism</span> <span class="cm-operator">=</span> <span class="cm-atom">true</span>;
}
<span class="cm-variable">speed</span> <span class="cm-operator">=</span> <span class="cm-number">0</span>;
<span class="cm-keyword">if</span> (<span class="cm-variable">speed</span> <span class="cm-operator">==</span> <span class="cm-atom">null</span>) {
<span class="cm-variable">speed</span> <span class="cm-operator">=</span> <span class="cm-number">15</span>;
}
<span class="cm-variable">footprints</span> <span class="cm-operator">=</span> <span class="cm-keyword">typeof</span> <span class="cm-variable">yeti</span> <span class="cm-operator">!==</span> <span class="cm-string">"undefined"</span> <span class="cm-operator">&amp;&amp;</span> <span class="cm-variable">yeti</span> <span class="cm-operator">!==</span> <span class="cm-atom">null</span> <span class="cm-operator">?</span> <span class="cm-variable">yeti</span> : <span class="cm-string">"bear"</span>;
</pre>
</div>
</div>
<div class="row">
<div class="col text-right">
<button type="button" class="btn btn-primary" data-action="run-code-example" data-example="existence" data-run="footprints"><small><svg class="play-button" viewBox="0 0 24 24">
<path d="M2.56-0.01v24.02L21.44 11.98 2.56-0.01z"></path>
</svg>
</small>footprints</button>
</div>
</div>
</aside>
<p>Note that if the compiler knows that <code>a</code> is in scope and therefore declared, <code>a?</code> compiles to <code>a != null</code>, <em>not</em> <code>a !== null</code>. The <code>!=</code> makes a loose comparison to <code>null</code>, which does double duty also comparing against <code>undefined</code>. The reverse also holds for <code>not a?</code> or <code>unless a?</code>.</p>
<aside class="code-example container-fluid bg-ribbed-dark" data-example="existence_declared">
<div class="row">
<div class="col-md-6 coffeescript-input-column">
<textarea class="coffeescript-input" id="existence_declared-coffee">major = 'Computer Science'
unless major?
signUpForClass 'Introduction to Wines'
</textarea>
<pre class="placeholder-code"><span class="cm-variable">major</span> <span class="cm-punctuation">=</span> <span class="cm-string">'Computer Science'</span>
<span class="cm-keyword">unless</span> <span class="cm-variable">major</span><span class="cm-operator">?</span>
<span class="cm-variable">signUpForClass</span> <span class="cm-string">'Introduction to Wines'</span>
</pre>
</div>
<div class="col-md-6 javascript-output-column">
<textarea class="javascript-output" id="existence_declared-js">var major;
major = 'Computer Science';
if (major == null) {
signUpForClass('Introduction to Wines');
}
</textarea>
<pre class="placeholder-code"><span class="cm-keyword">var</span> <span class="cm-def">major</span>;
<span class="cm-variable">major</span> <span class="cm-operator">=</span> <span class="cm-string">'Computer Science'</span>;
<span class="cm-keyword">if</span> (<span class="cm-variable">major</span> <span class="cm-operator">==</span> <span class="cm-atom">null</span>) {
<span class="cm-variable">signUpForClass</span>(<span class="cm-string">'Introduction to Wines'</span>);
}
</pre>
</div>
</div>
</aside>
<p>If a variable might be undeclared, the compiler does a thorough check. This is what JavaScript coders <em>should</em> be typing when they want to check if a mystery variable exists.</p>
<aside class="code-example container-fluid bg-ribbed-dark" data-example="existence_undeclared">
<div class="row">
<div class="col-md-6 coffeescript-input-column">
<textarea class="coffeescript-input" id="existence_undeclared-coffee">if window?
environment = 'browser (probably)'
</textarea>
<pre class="placeholder-code"><span class="cm-keyword">if</span> <span class="cm-variable">window</span><span class="cm-operator">?</span>
<span class="cm-variable">environment</span> <span class="cm-punctuation">=</span> <span class="cm-string">'browser (probably)'</span>
</pre>
</div>
<div class="col-md-6 javascript-output-column">
<textarea class="javascript-output" id="existence_undeclared-js">var environment;
if (typeof window !== "undefined" && window !== null) {
environment = 'browser (probably)';
}
</textarea>
<pre class="placeholder-code"><span class="cm-keyword">var</span> <span class="cm-def">environment</span>;
<span class="cm-keyword">if</span> (<span class="cm-keyword">typeof</span> <span class="cm-variable">window</span> <span class="cm-operator">!==</span> <span class="cm-string">"undefined"</span> <span class="cm-operator">&amp;&amp;</span> <span class="cm-variable">window</span> <span class="cm-operator">!==</span> <span class="cm-atom">null</span>) {
<span class="cm-variable">environment</span> <span class="cm-operator">=</span> <span class="cm-string">'browser (probably)'</span>;
}
</pre>
</div>
</div>
</aside>
<p>The accessor variant of the existential operator <code>?.</code> can be used to soak up null references in a chain of properties. Use it instead of the dot accessor <code>.</code> in cases where the base value may be <code>null</code> or <code>undefined</code>. If all of the properties exist then youll get the expected result, if the chain is broken, <code>undefined</code> is returned instead of the <code>TypeError</code> that would be raised otherwise.</p>
<aside class="code-example container-fluid bg-ribbed-dark" data-example="soaks">
<div class="row">
<div class="col-md-6 coffeescript-input-column">
<textarea class="coffeescript-input" id="soaks-coffee">zip = lottery.drawWinner?().address?.zipcode
</textarea>
<pre class="placeholder-code"><span class="cm-variable">zip</span> <span class="cm-punctuation">=</span> <span class="cm-variable">lottery</span><span class="cm-punctuation">.</span><span class="cm-property">drawWinner</span><span class="cm-operator">?</span><span class="cm-punctuation">().</span><span class="cm-property">address</span><span class="cm-operator">?</span><span class="cm-punctuation">.</span><span class="cm-property">zipcode</span>
</pre>
</div>
<div class="col-md-6 javascript-output-column">
<textarea class="javascript-output" id="soaks-js">var ref, zip;
zip = typeof lottery.drawWinner === "function" ? (ref = lottery.drawWinner().address) != null ? ref.zipcode : void 0 : void 0;
</textarea>
<pre class="placeholder-code"><span class="cm-keyword">var</span> <span class="cm-def">ref</span>, <span class="cm-def">zip</span>;
<span class="cm-variable">zip</span> <span class="cm-operator">=</span> <span class="cm-keyword">typeof</span> <span class="cm-variable">lottery</span>.<span class="cm-property">drawWinner</span> <span class="cm-operator">===</span> <span class="cm-string">"function"</span> <span class="cm-operator">?</span> (<span class="cm-variable">ref</span> <span class="cm-operator">=</span> <span class="cm-variable">lottery</span>.<span class="cm-property">drawWinner</span>().<span class="cm-property">address</span>) <span class="cm-operator">!=</span> <span class="cm-atom">null</span> <span class="cm-operator">?</span> <span class="cm-variable">ref</span>.<span class="cm-property">zipcode</span> : <span class="cm-keyword">void</span> <span class="cm-number">0</span> : <span class="cm-keyword">void</span> <span class="cm-number">0</span>;
</pre>
</div>
</div>
</aside>
<p>For completeness:</p>
<table>
<thead>
<tr>
<th>Example</th>
<th>Definition</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>a?</code></td>
<td>tests that <code>a</code> is in scope and <code>a != null</code></td>
</tr>
<tr>
<td><code>a ? b</code></td>
<td>returns <code>a</code> if <code>a</code> is in scope and <code>a != null</code>; otherwise, <code>b</code></td>
</tr>
<tr>
<td><code>a?.b</code> or <code>a?['b']</code></td>
<td>returns <code>a.b</code> if <code>a</code> is in scope and <code>a != null</code>; otherwise, <code>undefined</code></td>
</tr>
<tr>
<td><code>a?(b, c)</code> or <code>a? b, c</code></td>
<td>returns the result of calling <code>a</code> (with arguments <code>b</code> and <code>c</code>) if <code>a</code> is in scope and callable; otherwise, <code>undefined</code></td>
</tr>
<tr>
<td><code>a ?= b</code></td>
<td>assigns the value of <code>b</code> to <code>a</code> if <code>a</code> is not in scope or if <code>a == null</code>; produces the new value of <code>a</code></td>
</tr>
</tbody>
</table>
</section>
<section id="chaining">
<h2>Chaining Function Calls</h2>
<p>Leading <code>.</code> closes all open calls, allowing for simpler chaining syntax.</p>
<aside class="code-example container-fluid bg-ribbed-dark" data-example="chaining">
<div class="row">
<div class="col-md-6 coffeescript-input-column">
<textarea class="coffeescript-input" id="chaining-coffee">$ 'body'
.click (e) ->
$ '.box'
.fadeIn 'fast'
.addClass 'show'
.css 'background', 'white'
</textarea>
<pre class="placeholder-code"><span class="cm-variable">$</span> <span class="cm-string">'body'</span>
<span class="cm-punctuation">.</span><span class="cm-property">click</span> <span class="cm-punctuation">(</span><span class="cm-variable">e</span><span class="cm-punctuation">)</span> <span class="cm-operator">-></span>
<span class="cm-variable">$</span> <span class="cm-string">'.box'</span>
<span class="cm-punctuation">.</span><span class="cm-property">fadeIn</span> <span class="cm-string">'fast'</span>
<span class="cm-punctuation">.</span><span class="cm-property">addClass</span> <span class="cm-string">'show'</span>
<span class="cm-punctuation">.</span><span class="cm-property">css</span> <span class="cm-string">'background'</span><span class="cm-punctuation">,</span> <span class="cm-string">'white'</span>
</pre>
</div>
<div class="col-md-6 javascript-output-column">
<textarea class="javascript-output" id="chaining-js">$('body').click(function(e) {
return $('.box').fadeIn('fast').addClass('show');
}).css('background', 'white');
</textarea>
<pre class="placeholder-code"><span class="cm-variable">$</span>(<span class="cm-string">'body'</span>).<span class="cm-property">click</span>(<span class="cm-keyword">function</span>(<span class="cm-def">e</span>) {
<span class="cm-keyword">return</span> <span class="cm-variable">$</span>(<span class="cm-string">'.box'</span>).<span class="cm-property">fadeIn</span>(<span class="cm-string">'fast'</span>).<span class="cm-property">addClass</span>(<span class="cm-string">'show'</span>);
}).<span class="cm-property">css</span>(<span class="cm-string">'background'</span>, <span class="cm-string">'white'</span>);
</pre>
</div>
</div>
</aside>
</section>
<section id="destructuring">
<h2>Destructuring Assignment</h2>
<p>Just like JavaScript (since ES2015), CoffeeScript has destructuring assignment syntax. When you assign an array or object literal to a value, CoffeeScript breaks up and matches both sides against each other, assigning the values on the right to the variables on the left. In the simplest case, it can be used for parallel assignment:</p>
<aside class="code-example container-fluid bg-ribbed-dark" data-example="parallel_assignment">
<div class="row">
<div class="col-md-6 coffeescript-input-column">
<textarea class="coffeescript-input" id="parallel_assignment-coffee">theBait = 1000
theSwitch = 0
[theBait, theSwitch] = [theSwitch, theBait]
</textarea>
<pre class="placeholder-code"><span class="cm-variable">theBait</span> <span class="cm-punctuation">=</span> <span class="cm-number">1000</span>
<span class="cm-variable">theSwitch</span> <span class="cm-punctuation">=</span> <span class="cm-number">0</span>
<span class="cm-punctuation">[</span><span class="cm-variable">theBait</span><span class="cm-punctuation">,</span> <span class="cm-variable">theSwitch</span><span class="cm-punctuation">]</span> <span class="cm-punctuation">=</span> <span class="cm-punctuation">[</span><span class="cm-variable">theSwitch</span><span class="cm-punctuation">,</span> <span class="cm-variable">theBait</span><span class="cm-punctuation">]</span>
</pre>
</div>
<div class="col-md-6 javascript-output-column">
<textarea class="javascript-output" id="parallel_assignment-js">var theBait, theSwitch;
theBait = 1000;
theSwitch = 0;
[theBait, theSwitch] = [theSwitch, theBait];
</textarea>
<pre class="placeholder-code"><span class="cm-keyword">var</span> <span class="cm-def">theBait</span>, <span class="cm-def">theSwitch</span>;
<span class="cm-variable">theBait</span> <span class="cm-operator">=</span> <span class="cm-number">1000</span>;
<span class="cm-variable">theSwitch</span> <span class="cm-operator">=</span> <span class="cm-number">0</span>;
[<span class="cm-variable">theBait</span>, <span class="cm-variable">theSwitch</span>] <span class="cm-operator">=</span> [<span class="cm-variable">theSwitch</span>, <span class="cm-variable">theBait</span>];
</pre>
</div>
</div>
<div class="row">
<div class="col text-right">
<button type="button" class="btn btn-primary" data-action="run-code-example" data-example="parallel_assignment" data-run="theBait"><small><svg class="play-button" viewBox="0 0 24 24">
<path d="M2.56-0.01v24.02L21.44 11.98 2.56-0.01z"></path>
</svg>
</small>theBait</button>
</div>
</div>
</aside>
<p>But its also helpful for dealing with functions that return multiple values.</p>
<aside class="code-example container-fluid bg-ribbed-dark" data-example="multiple_return_values">
<div class="row">
<div class="col-md-6 coffeescript-input-column">
<textarea class="coffeescript-input" id="multiple_return_values-coffee">weatherReport = (location) ->
# Make an Ajax request to fetch the weather...
[location, 72, "Mostly Sunny"]
[city, temp, forecast] = weatherReport "Berkeley, CA"
</textarea>
<pre class="placeholder-code"><span class="cm-variable">weatherReport</span> <span class="cm-punctuation">=</span> <span class="cm-punctuation">(</span><span class="cm-variable">location</span><span class="cm-punctuation">)</span> <span class="cm-operator">-></span>
<span class="cm-comment"># Make an Ajax request to fetch the weather...</span>
<span class="cm-punctuation">[</span><span class="cm-variable">location</span><span class="cm-punctuation">,</span> <span class="cm-number">72</span><span class="cm-punctuation">,</span> <span class="cm-string">"Mostly Sunny"</span><span class="cm-punctuation">]</span>
<span class="cm-punctuation">[</span><span class="cm-variable">city</span><span class="cm-punctuation">,</span> <span class="cm-variable">temp</span><span class="cm-punctuation">,</span> <span class="cm-variable">forecast</span><span class="cm-punctuation">]</span> <span class="cm-punctuation">=</span> <span class="cm-variable">weatherReport</span> <span class="cm-string">"Berkeley, CA"</span>
</pre>
</div>
<div class="col-md-6 javascript-output-column">
<textarea class="javascript-output" id="multiple_return_values-js">var city, forecast, temp, weatherReport;
weatherReport = function(location) {
// Make an Ajax request to fetch the weather...
return [location, 72, "Mostly Sunny"];
};
[city, temp, forecast] = weatherReport("Berkeley, CA");
</textarea>
<pre class="placeholder-code"><span class="cm-keyword">var</span> <span class="cm-def">city</span>, <span class="cm-def">forecast</span>, <span class="cm-def">temp</span>, <span class="cm-def">weatherReport</span>;
<span class="cm-variable">weatherReport</span> <span class="cm-operator">=</span> <span class="cm-keyword">function</span>(<span class="cm-def">location</span>) {
<span class="cm-comment">// Make an Ajax request to fetch the weather...</span>
<span class="cm-keyword">return</span> [<span class="cm-variable-2">location</span>, <span class="cm-number">72</span>, <span class="cm-string">"Mostly Sunny"</span>];
};
[<span class="cm-variable">city</span>, <span class="cm-variable">temp</span>, <span class="cm-variable">forecast</span>] <span class="cm-operator">=</span> <span class="cm-variable">weatherReport</span>(<span class="cm-string">"Berkeley, CA"</span>);
</pre>
</div>
</div>
<div class="row">
<div class="col text-right">
<button type="button" class="btn btn-primary" data-action="run-code-example" data-example="multiple_return_values" data-run="forecast"><small><svg class="play-button" viewBox="0 0 24 24">
<path d="M2.56-0.01v24.02L21.44 11.98 2.56-0.01z"></path>
</svg>
</small>forecast</button>
</div>
</div>
</aside>
<p>Destructuring assignment can be used with any depth of array and object nesting, to help pull out deeply nested properties.</p>
<aside class="code-example container-fluid bg-ribbed-dark" data-example="object_extraction">
<div class="row">
<div class="col-md-6 coffeescript-input-column">
<textarea class="coffeescript-input" id="object_extraction-coffee">futurists =
sculptor: "Umberto Boccioni"
painter: "Vladimir Burliuk"
poet:
name: "F.T. Marinetti"
address: [
"Via Roma 42R"
"Bellagio, Italy 22021"
]
{sculptor} = futurists
{poet: {name, address: [street, city]}} = futurists
</textarea>
<pre class="placeholder-code"><span class="cm-variable">futurists</span> <span class="cm-punctuation">=</span>
<span class="cm-indent"> </span><span class="cm-variable">sculptor</span><span class="cm-punctuation">:</span> <span class="cm-string">"Umberto Boccioni"</span>
<span class="cm-variable">painter</span><span class="cm-punctuation">:</span> <span class="cm-string">"Vladimir Burliuk"</span>
<span class="cm-variable">poet</span><span class="cm-punctuation">:</span>
<span class="cm-indent"> </span><span class="cm-variable">name</span><span class="cm-punctuation">:</span> <span class="cm-string">"F.T. Marinetti"</span>
<span class="cm-variable">address</span><span class="cm-punctuation">:</span> <span class="cm-punctuation">[</span>
<span class="cm-string">"Via Roma 42R"</span>
<span class="cm-string">"Bellagio, Italy 22021"</span>
<span class="cm-dedent"> </span><span class="cm-punctuation">]</span>
<span class="cm-punctuation">{</span><span class="cm-variable">sculptor</span><span class="cm-punctuation">}</span> <span class="cm-punctuation">=</span> <span class="cm-variable">futurists</span>
<span class="cm-punctuation">{</span><span class="cm-variable">poet</span><span class="cm-punctuation">:</span> <span class="cm-punctuation">{</span><span class="cm-variable">name</span><span class="cm-punctuation">,</span> <span class="cm-variable">address</span><span class="cm-punctuation">:</span> <span class="cm-punctuation">[</span><span class="cm-variable">street</span><span class="cm-punctuation">,</span> <span class="cm-variable">city</span><span class="cm-punctuation">]}}</span> <span class="cm-punctuation">=</span> <span class="cm-variable">futurists</span>
</pre>
</div>
<div class="col-md-6 javascript-output-column">
<textarea class="javascript-output" id="object_extraction-js">var city, futurists, name, sculptor, street;
futurists = {
sculptor: "Umberto Boccioni",
painter: "Vladimir Burliuk",
poet: {
name: "F.T. Marinetti",
address: ["Via Roma 42R", "Bellagio, Italy 22021"]
}
};
({sculptor} = futurists);
({
poet: {
name,
address: [street, city]
}
} = futurists);
</textarea>
<pre class="placeholder-code"><span class="cm-keyword">var</span> <span class="cm-def">city</span>, <span class="cm-def">futurists</span>, <span class="cm-def">name</span>, <span class="cm-def">sculptor</span>, <span class="cm-def">street</span>;
<span class="cm-variable">futurists</span> <span class="cm-operator">=</span> {
<span class="cm-property">sculptor</span>: <span class="cm-string">"Umberto Boccioni"</span>,
<span class="cm-property">painter</span>: <span class="cm-string">"Vladimir Burliuk"</span>,
<span class="cm-property">poet</span>: {
<span class="cm-property">name</span>: <span class="cm-string">"F.T. Marinetti"</span>,
<span class="cm-property">address</span>: [<span class="cm-string">"Via Roma 42R"</span>, <span class="cm-string">"Bellagio, Italy 22021"</span>]
}
};
({<span class="cm-property">sculptor</span>} <span class="cm-operator">=</span> <span class="cm-variable">futurists</span>);
({
<span class="cm-property">poet</span>: {
<span class="cm-property">name</span>,
<span class="cm-property">address</span>: [<span class="cm-variable">street</span>, <span class="cm-variable">city</span>]
}
} <span class="cm-operator">=</span> <span class="cm-variable">futurists</span>);
</pre>
</div>
</div>
<div class="row">
<div class="col text-right">
<button type="button" class="btn btn-primary" data-action="run-code-example" data-example="object_extraction" data-run="name%20+%20%22-%22%20+%20street"><small><svg class="play-button" viewBox="0 0 24 24">
<path d="M2.56-0.01v24.02L21.44 11.98 2.56-0.01z"></path>
</svg>
</small>name + &quot;-&quot; + street</button>
</div>
</div>
</aside>
<p>Destructuring assignment can even be combined with splats.</p>
<aside class="code-example container-fluid bg-ribbed-dark" data-example="patterns_and_splats">
<div class="row">
<div class="col-md-6 coffeescript-input-column">
<textarea class="coffeescript-input" id="patterns_and_splats-coffee">tag = "<impossible>"
[open, contents..., close] = tag.split("")
</textarea>
<pre class="placeholder-code"><span class="cm-variable">tag</span> <span class="cm-punctuation">=</span> <span class="cm-string">"&lt;impossible>"</span>
<span class="cm-punctuation">[</span><span class="cm-variable">open</span><span class="cm-punctuation">,</span> <span class="cm-variable">contents</span><span class="cm-punctuation">...,</span> <span class="cm-variable">close</span><span class="cm-punctuation">]</span> <span class="cm-punctuation">=</span> <span class="cm-variable">tag</span><span class="cm-punctuation">.</span><span class="cm-property">split</span><span class="cm-punctuation">(</span><span class="cm-string">""</span><span class="cm-punctuation">)</span>
</pre>
</div>
<div class="col-md-6 javascript-output-column">
<textarea class="javascript-output" id="patterns_and_splats-js">var close, contents, open, ref, tag,
splice = [].splice;
tag = "<impossible>";
ref = tag.split(""), [open, ...contents] = ref, [close] = splice.call(contents, -1);
</textarea>
<pre class="placeholder-code"><span class="cm-keyword">var</span> <span class="cm-def">close</span>, <span class="cm-def">contents</span>, <span class="cm-def">open</span>, <span class="cm-def">ref</span>, <span class="cm-def">tag</span>,
<span class="cm-def">splice</span> <span class="cm-operator">=</span> [].<span class="cm-property">splice</span>;
<span class="cm-variable">tag</span> <span class="cm-operator">=</span> <span class="cm-string">"&lt;impossible>"</span>;
<span class="cm-variable">ref</span> <span class="cm-operator">=</span> <span class="cm-variable">tag</span>.<span class="cm-property">split</span>(<span class="cm-string">""</span>), [<span class="cm-variable">open</span>, <span class="cm-meta">...</span><span class="cm-variable">contents</span>] <span class="cm-operator">=</span> <span class="cm-variable">ref</span>, [<span class="cm-variable">close</span>] <span class="cm-operator">=</span> <span class="cm-variable">splice</span>.<span class="cm-property">call</span>(<span class="cm-variable">contents</span>, <span class="cm-operator">-</span><span class="cm-number">1</span>);
</pre>
</div>
</div>
<div class="row">
<div class="col text-right">
<button type="button" class="btn btn-primary" data-action="run-code-example" data-example="patterns_and_splats" data-run="contents.join%28%22%22%29"><small><svg class="play-button" viewBox="0 0 24 24">
<path d="M2.56-0.01v24.02L21.44 11.98 2.56-0.01z"></path>
</svg>
</small>contents.join(&quot;&quot;)</button>
</div>
</div>
</aside>
<p>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.</p>
<aside class="code-example container-fluid bg-ribbed-dark" data-example="expansion">
<div class="row">
<div class="col-md-6 coffeescript-input-column">
<textarea class="coffeescript-input" id="expansion-coffee">text = "Every literary critic believes he will
outwit history and have the last word"
[first, ..., last] = text.split " "
</textarea>
<pre class="placeholder-code"><span class="cm-variable">text</span> <span class="cm-punctuation">=</span> <span class="cm-string">"Every literary critic believes he will</span>
<span class="cm-string"> outwit history and have the last word"</span>
<span class="cm-punctuation">[</span><span class="cm-variable">first</span><span class="cm-punctuation">,</span> <span class="cm-punctuation">...,</span> <span class="cm-variable">last</span><span class="cm-punctuation">]</span> <span class="cm-punctuation">=</span> <span class="cm-variable">text</span><span class="cm-punctuation">.</span><span class="cm-property">split</span> <span class="cm-string">" "</span>
</pre>
</div>
<div class="col-md-6 javascript-output-column">
<textarea class="javascript-output" id="expansion-js">var first, last, ref, text,
slice = [].slice;
text = "Every literary critic believes he will outwit history and have the last word";
ref = text.split(" "), [first] = ref, [last] = slice.call(ref, -1);
</textarea>
<pre class="placeholder-code"><span class="cm-keyword">var</span> <span class="cm-def">first</span>, <span class="cm-def">last</span>, <span class="cm-def">ref</span>, <span class="cm-def">text</span>,
<span class="cm-def">slice</span> <span class="cm-operator">=</span> [].<span class="cm-property">slice</span>;
<span class="cm-variable">text</span> <span class="cm-operator">=</span> <span class="cm-string">"Every literary critic believes he will outwit history and have the last word"</span>;
<span class="cm-variable">ref</span> <span class="cm-operator">=</span> <span class="cm-variable">text</span>.<span class="cm-property">split</span>(<span class="cm-string">" "</span>), [<span class="cm-variable">first</span>] <span class="cm-operator">=</span> <span class="cm-variable">ref</span>, [<span class="cm-variable">last</span>] <span class="cm-operator">=</span> <span class="cm-variable">slice</span>.<span class="cm-property">call</span>(<span class="cm-variable">ref</span>, <span class="cm-operator">-</span><span class="cm-number">1</span>);
</pre>
</div>
</div>
<div class="row">
<div class="col text-right">
<button type="button" class="btn btn-primary" data-action="run-code-example" data-example="expansion" data-run="first%20+%20%22%20%22%20+%20last"><small><svg class="play-button" viewBox="0 0 24 24">
<path d="M2.56-0.01v24.02L21.44 11.98 2.56-0.01z"></path>
</svg>
</small>first + &quot; &quot; + last</button>
</div>
</div>
</aside>
<p>Destructuring assignment is also useful when combined with class constructors to assign properties to your instance from an options object passed to the constructor.</p>
<aside class="code-example container-fluid bg-ribbed-dark" data-example="constructor_destructuring">
<div class="row">
<div class="col-md-6 coffeescript-input-column">
<textarea class="coffeescript-input" id="constructor_destructuring-coffee">class Person
constructor: (options) ->
{@name, @age, @height = 'average'} = options
tim = new Person name: 'Tim', age: 4
</textarea>
<pre class="placeholder-code"><span class="cm-keyword">class</span> <span class="cm-variable">Person</span>
<span class="cm-variable">constructor</span><span class="cm-punctuation">:</span> <span class="cm-punctuation">(</span><span class="cm-variable">options</span><span class="cm-punctuation">)</span> <span class="cm-operator">-></span>
<span class="cm-punctuation">{</span><span class="cm-property">@name</span><span class="cm-punctuation">,</span> <span class="cm-property">@age</span><span class="cm-punctuation">,</span> <span class="cm-property">@height</span> <span class="cm-punctuation">=</span> <span class="cm-string">'average'</span><span class="cm-punctuation">}</span> <span class="cm-punctuation">=</span> <span class="cm-variable">options</span>
<span class="cm-variable">tim</span> <span class="cm-punctuation">=</span> <span class="cm-keyword">new</span> <span class="cm-variable">Person</span> <span class="cm-variable">name</span><span class="cm-punctuation">:</span> <span class="cm-string">'Tim'</span><span class="cm-punctuation">,</span> <span class="cm-variable">age</span><span class="cm-punctuation">:</span> <span class="cm-number">4</span>
</pre>
</div>
<div class="col-md-6 javascript-output-column">
<textarea class="javascript-output" id="constructor_destructuring-js">var Person, tim;
Person = class Person {
constructor(options) {
({name: this.name, age: this.age, height: this.height = 'average'} = options);
}
};
tim = new Person({
name: 'Tim',
age: 4
});
</textarea>
<pre class="placeholder-code"><span class="cm-keyword">var</span> <span class="cm-def">Person</span>, <span class="cm-def">tim</span>;
<span class="cm-variable">Person</span> <span class="cm-operator">=</span> <span class="cm-keyword">class</span> <span class="cm-def">Person</span> {
<span class="cm-property">constructor</span>(<span class="cm-def">options</span>) {
({<span class="cm-property">name</span>: <span class="cm-keyword">this</span>.<span class="cm-property">name</span>, <span class="cm-property">age</span>: <span class="cm-keyword">this</span>.<span class="cm-property">age</span>, <span class="cm-property">height</span>: <span class="cm-keyword">this</span>.<span class="cm-property">height</span> <span class="cm-operator">=</span> <span class="cm-string">'average'</span>} <span class="cm-operator">=</span> <span class="cm-variable-2">options</span>);
}
};
<span class="cm-variable">tim</span> <span class="cm-operator">=</span> <span class="cm-keyword">new</span> <span class="cm-variable">Person</span>({
<span class="cm-property">name</span>: <span class="cm-string">'Tim'</span>,
<span class="cm-property">age</span>: <span class="cm-number">4</span>
});
</pre>
</div>
</div>
<div class="row">
<div class="col text-right">
<button type="button" class="btn btn-primary" data-action="run-code-example" data-example="constructor_destructuring" data-run="tim.age%20+%20%22%20%22%20+%20tim.height"><small><svg class="play-button" viewBox="0 0 24 24">
<path d="M2.56-0.01v24.02L21.44 11.98 2.56-0.01z"></path>
</svg>
</small>tim.age + &quot; &quot; + tim.height</button>
</div>
</div>
</aside>
<p>The above example also demonstrates that if properties are missing in the destructured object or array, you can, just like in JavaScript, provide defaults. Note though that unlike with the existential operator, the default is only applied with the value is missing or <code>undefined</code><a href="#breaking-changes-default-values">passing <code>null</code> will set a value of <code>null</code></a>, not the default.</p>
</section>
<section id="fat-arrow">
<h2>Bound (Fat Arrow) Functions</h2>
<p>In JavaScript, the <code>this</code> keyword is dynamically scoped to mean the object that the current function is attached to. If you pass a function as a callback or attach it to a different object, the original value of <code>this</code> will be lost. If youre not familiar with this behavior, <a href="https://web.archive.org/web/20150316122013/http://www.digital-web.com/articles/scope_in_javascript">this Digital Web article</a> gives a good overview of the quirks.</p>
<p>The fat arrow <code>=&gt;</code> can be used to both define a function, and to bind it to the current value of <code>this</code>, right on the spot. This is helpful when using callback-based libraries like Prototype or jQuery, for creating iterator functions to pass to <code>each</code>, or event-handler functions to use with <code>on</code>. Functions created with the fat arrow are able to access properties of the <code>this</code> where theyre defined.</p>
<aside class="code-example container-fluid bg-ribbed-dark" data-example="fat_arrow">
<div class="row">
<div class="col-md-6 coffeescript-input-column">
<textarea class="coffeescript-input" id="fat_arrow-coffee">Account = (customer, cart) ->
@customer = customer
@cart = cart
$('.shopping_cart').on 'click', (event) =>
@customer.purchase @cart
</textarea>
<pre class="placeholder-code"><span class="cm-variable">Account</span> <span class="cm-punctuation">=</span> <span class="cm-punctuation">(</span><span class="cm-variable">customer</span><span class="cm-punctuation">,</span> <span class="cm-variable">cart</span><span class="cm-punctuation">)</span> <span class="cm-operator">-></span>
<span class="cm-property">@customer</span> <span class="cm-punctuation">=</span> <span class="cm-variable">customer</span>
<span class="cm-property">@cart</span> <span class="cm-punctuation">=</span> <span class="cm-variable">cart</span>
<span class="cm-variable">$</span><span class="cm-punctuation">(</span><span class="cm-string">'.shopping_cart'</span><span class="cm-punctuation">).</span><span class="cm-atom">on</span> <span class="cm-string">'click'</span><span class="cm-punctuation">,</span> <span class="cm-punctuation">(</span><span class="cm-variable">event</span><span class="cm-punctuation">)</span> <span class="cm-operator">=></span>
<span class="cm-property">@customer</span><span class="cm-punctuation">.</span><span class="cm-property">purchase</span> <span class="cm-property">@cart</span>
</pre>
</div>
<div class="col-md-6 javascript-output-column">
<textarea class="javascript-output" id="fat_arrow-js">var Account;
Account = function(customer, cart) {
this.customer = customer;
this.cart = cart;
return $('.shopping_cart').on('click', (event) => {
return this.customer.purchase(this.cart);
});
};
</textarea>
<pre class="placeholder-code"><span class="cm-keyword">var</span> <span class="cm-def">Account</span>;
<span class="cm-variable">Account</span> <span class="cm-operator">=</span> <span class="cm-keyword">function</span>(<span class="cm-def">customer</span>, <span class="cm-def">cart</span>) {
<span class="cm-keyword">this</span>.<span class="cm-property">customer</span> <span class="cm-operator">=</span> <span class="cm-variable-2">customer</span>;
<span class="cm-keyword">this</span>.<span class="cm-property">cart</span> <span class="cm-operator">=</span> <span class="cm-variable-2">cart</span>;
<span class="cm-keyword">return</span> <span class="cm-variable">$</span>(<span class="cm-string">'.shopping_cart'</span>).<span class="cm-property">on</span>(<span class="cm-string">'click'</span>, (<span class="cm-def">event</span>) <span class="cm-operator">=></span> {
<span class="cm-keyword">return</span> <span class="cm-keyword">this</span>.<span class="cm-property">customer</span>.<span class="cm-property">purchase</span>(<span class="cm-keyword">this</span>.<span class="cm-property">cart</span>);
});
};
</pre>
</div>
</div>
</aside>
<p>If we had used <code>-&gt;</code> in the callback above, <code>@customer</code> would have referred to the undefined “customer” property of the DOM element, and trying to call <code>purchase()</code> on it would have raised an exception.</p>
<p>The fat arrow was one of the most popular features of CoffeeScript, and ES2015 <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions">adopted it</a>; so CoffeeScript 2 compiles <code>=&gt;</code> to ES <code>=&gt;</code>.</p>
</section>
<section id="generators">
<h2>Generator Functions</h2>
<p>CoffeeScript supports ES2015 <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function*">generator functions</a> through the <code>yield</code> keyword. Theres no <code>function*(){}</code> nonsense — a generator in CoffeeScript is simply a function that yields.</p>
<aside class="code-example container-fluid bg-ribbed-dark" data-example="generators">
<div class="row">
<div class="col-md-6 coffeescript-input-column">
<textarea class="coffeescript-input" id="generators-coffee">perfectSquares = ->
num = 0
loop
num += 1
yield num * num
return
window.ps or= perfectSquares()
</textarea>
<pre class="placeholder-code"><span class="cm-variable">perfectSquares</span> <span class="cm-punctuation">=</span> <span class="cm-operator">-></span>
<span class="cm-variable">num</span> <span class="cm-punctuation">=</span> <span class="cm-number">0</span>
<span class="cm-keyword">loop</span>
<span class="cm-variable">num</span> <span class="cm-operator">+=</span> <span class="cm-number">1</span>
<span class="cm-variable">yield</span> <span class="cm-variable">num</span> <span class="cm-operator">*</span> <span class="cm-variable">num</span>
<span class="cm-dedent"> </span><span class="cm-keyword">return</span>
<span class="cm-variable">window</span><span class="cm-punctuation">.</span><span class="cm-property">ps</span> <span class="cm-operator">or=</span> <span class="cm-variable">perfectSquares</span><span class="cm-punctuation">()</span>
</pre>
</div>
<div class="col-md-6 javascript-output-column">
<textarea class="javascript-output" id="generators-js">var perfectSquares;
perfectSquares = function*() {
var num;
num = 0;
while (true) {
num += 1;
yield num * num;
}
};
window.ps || (window.ps = perfectSquares());
</textarea>
<pre class="placeholder-code"><span class="cm-keyword">var</span> <span class="cm-def">perfectSquares</span>;
<span class="cm-variable">perfectSquares</span> <span class="cm-operator">=</span> <span class="cm-keyword">function*</span>() {
<span class="cm-keyword">var</span> <span class="cm-def">num</span>;
<span class="cm-variable-2">num</span> <span class="cm-operator">=</span> <span class="cm-number">0</span>;
<span class="cm-keyword">while</span> (<span class="cm-atom">true</span>) {
<span class="cm-variable-2">num</span> <span class="cm-operator">+=</span> <span class="cm-number">1</span>;
<span class="cm-keyword">yield</span> <span class="cm-variable-2">num</span> <span class="cm-operator">*</span> <span class="cm-variable-2">num</span>;
}
};
<span class="cm-variable">window</span>.<span class="cm-property">ps</span> <span class="cm-operator">||</span> (<span class="cm-variable">window</span>.<span class="cm-property">ps</span> <span class="cm-operator">=</span> <span class="cm-variable">perfectSquares</span>());
</pre>
</div>
</div>
<div class="row">
<div class="col text-right">
<button type="button" class="btn btn-primary" data-action="run-code-example" data-example="generators" data-run="ps.next%28%29.value"><small><svg class="play-button" viewBox="0 0 24 24">
<path d="M2.56-0.01v24.02L21.44 11.98 2.56-0.01z"></path>
</svg>
</small>ps.next().value</button>
</div>
</div>
</aside>
<p><code>yield*</code> is called <code>yield from</code>, and <code>yield return</code> may be used if you need to force a generator that doesnt yield.</p>
<div id="generator-iteration" class="bookmark"></div>
<p>You can iterate over a generator function using <code>for…from</code>.</p>
<aside class="code-example container-fluid bg-ribbed-dark" data-example="generator_iteration">
<div class="row">
<div class="col-md-6 coffeescript-input-column">
<textarea class="coffeescript-input" id="generator_iteration-coffee">fibonacci = ->
[previous, current] = [1, 1]
loop
[previous, current] = [current, previous + current]
yield current
return
getFibonacciNumbers = (length) ->
results = [1]
for n from fibonacci()
results.push n
break if results.length is length
results
</textarea>
<pre class="placeholder-code"><span class="cm-variable">fibonacci</span> <span class="cm-punctuation">=</span> <span class="cm-operator">-></span>
<span class="cm-punctuation">[</span><span class="cm-variable">previous</span><span class="cm-punctuation">,</span> <span class="cm-variable">current</span><span class="cm-punctuation">]</span> <span class="cm-punctuation">=</span> <span class="cm-punctuation">[</span><span class="cm-number">1</span><span class="cm-punctuation">,</span> <span class="cm-number">1</span><span class="cm-punctuation">]</span>
<span class="cm-keyword">loop</span>
<span class="cm-punctuation">[</span><span class="cm-variable">previous</span><span class="cm-punctuation">,</span> <span class="cm-variable">current</span><span class="cm-punctuation">]</span> <span class="cm-punctuation">=</span> <span class="cm-punctuation">[</span><span class="cm-variable">current</span><span class="cm-punctuation">,</span> <span class="cm-variable">previous</span> <span class="cm-operator">+</span> <span class="cm-variable">current</span><span class="cm-punctuation">]</span>
<span class="cm-variable">yield</span> <span class="cm-variable">current</span>
<span class="cm-dedent"> </span><span class="cm-keyword">return</span>
<span class="cm-variable">getFibonacciNumbers</span> <span class="cm-punctuation">=</span> <span class="cm-punctuation">(</span><span class="cm-variable">length</span><span class="cm-punctuation">)</span> <span class="cm-operator">-></span>
<span class="cm-variable">results</span> <span class="cm-punctuation">=</span> <span class="cm-punctuation">[</span><span class="cm-number">1</span><span class="cm-punctuation">]</span>
<span class="cm-keyword">for</span> <span class="cm-variable">n</span> <span class="cm-variable">from</span> <span class="cm-variable">fibonacci</span><span class="cm-punctuation">()</span>
<span class="cm-variable">results</span><span class="cm-punctuation">.</span><span class="cm-property">push</span> <span class="cm-variable">n</span>
<span class="cm-keyword">break</span> <span class="cm-keyword">if</span> <span class="cm-variable">results</span><span class="cm-punctuation">.</span><span class="cm-property">length</span> <span class="cm-operator">is</span> <span class="cm-variable">length</span>
<span class="cm-dedent"> </span><span class="cm-variable">results</span>
</pre>
</div>
<div class="col-md-6 javascript-output-column">
<textarea class="javascript-output" id="generator_iteration-js">var fibonacci, getFibonacciNumbers;
fibonacci = function*() {
var current, previous;
[previous, current] = [1, 1];
while (true) {
[previous, current] = [current, previous + current];
yield current;
}
};
getFibonacciNumbers = function(length) {
var n, ref, results;
results = [1];
ref = fibonacci();
for (n of ref) {
results.push(n);
if (results.length === length) {
break;
}
}
return results;
};
</textarea>
<pre class="placeholder-code"><span class="cm-keyword">var</span> <span class="cm-def">fibonacci</span>, <span class="cm-def">getFibonacciNumbers</span>;
<span class="cm-variable">fibonacci</span> <span class="cm-operator">=</span> <span class="cm-keyword">function*</span>() {
<span class="cm-keyword">var</span> <span class="cm-def">current</span>, <span class="cm-def">previous</span>;
[<span class="cm-variable-2">previous</span>, <span class="cm-variable-2">current</span>] <span class="cm-operator">=</span> [<span class="cm-number">1</span>, <span class="cm-number">1</span>];
<span class="cm-keyword">while</span> (<span class="cm-atom">true</span>) {
[<span class="cm-variable-2">previous</span>, <span class="cm-variable-2">current</span>] <span class="cm-operator">=</span> [<span class="cm-variable-2">current</span>, <span class="cm-variable-2">previous</span> <span class="cm-operator">+</span> <span class="cm-variable-2">current</span>];
<span class="cm-keyword">yield</span> <span class="cm-variable-2">current</span>;
}
};
<span class="cm-variable">getFibonacciNumbers</span> <span class="cm-operator">=</span> <span class="cm-keyword">function</span>(<span class="cm-def">length</span>) {
<span class="cm-keyword">var</span> <span class="cm-def">n</span>, <span class="cm-def">ref</span>, <span class="cm-def">results</span>;
<span class="cm-variable-2">results</span> <span class="cm-operator">=</span> [<span class="cm-number">1</span>];
<span class="cm-variable-2">ref</span> <span class="cm-operator">=</span> <span class="cm-variable">fibonacci</span>();
<span class="cm-keyword">for</span> (<span class="cm-variable-2">n</span> <span class="cm-keyword">of</span> <span class="cm-variable-2">ref</span>) {
<span class="cm-variable-2">results</span>.<span class="cm-property">push</span>(<span class="cm-variable-2">n</span>);
<span class="cm-keyword">if</span> (<span class="cm-variable-2">results</span>.<span class="cm-property">length</span> <span class="cm-operator">===</span> <span class="cm-variable-2">length</span>) {
<span class="cm-keyword">break</span>;
}
}
<span class="cm-keyword">return</span> <span class="cm-variable-2">results</span>;
};
</pre>
</div>
</div>
<div class="row">
<div class="col text-right">
<button type="button" class="btn btn-primary" data-action="run-code-example" data-example="generator_iteration" data-run="getFibonacciNumbers%2810%29"><small><svg class="play-button" viewBox="0 0 24 24">
<path d="M2.56-0.01v24.02L21.44 11.98 2.56-0.01z"></path>
</svg>
</small>getFibonacciNumbers(10)</button>
</div>
</div>
</aside>
</section>
<section id="async-functions">
<h2>Async Functions</h2>
<p>ES2017s <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function">async functions</a> are supported through the <code>await</code> keyword. Like with generators, theres no need for an <code>async</code> keyword; an async function in CoffeeScript is simply a function that awaits.</p>
<p>Similar to how <code>yield return</code> forces a generator, <code>await return</code> may be used to force a function to be async.</p>
<aside class="code-example container-fluid bg-ribbed-dark" data-example="async">
<div class="row">
<div class="col-md-6 coffeescript-input-column">
<textarea class="coffeescript-input" id="async-coffee"># Your browser must support async/await and speech synthesis
# to run this example.
sleep = (ms) ->
new Promise (resolve) ->
window.setTimeout resolve, ms
say = (text) ->
window.speechSynthesis.cancel()
window.speechSynthesis.speak new SpeechSynthesisUtterance text
countdown = (seconds) ->
for i in [seconds..1]
say i
await sleep 1000 # wait one second
say "Blastoff!"
countdown 3
</textarea>
<pre class="placeholder-code"><span class="cm-comment"># Your browser must support async/await and speech synthesis</span>
<span class="cm-comment"># to run this example.</span>
<span class="cm-variable">sleep</span> <span class="cm-punctuation">=</span> <span class="cm-punctuation">(</span><span class="cm-variable">ms</span><span class="cm-punctuation">)</span> <span class="cm-operator">-></span>
<span class="cm-keyword">new</span> <span class="cm-variable">Promise</span> <span class="cm-punctuation">(</span><span class="cm-variable">resolve</span><span class="cm-punctuation">)</span> <span class="cm-operator">-></span>
<span class="cm-variable">window</span><span class="cm-punctuation">.</span><span class="cm-property">setTimeout</span> <span class="cm-variable">resolve</span><span class="cm-punctuation">,</span> <span class="cm-variable">ms</span>
<span class="cm-variable">say</span> <span class="cm-punctuation">=</span> <span class="cm-punctuation">(</span><span class="cm-variable">text</span><span class="cm-punctuation">)</span> <span class="cm-operator">-></span>
<span class="cm-variable">window</span><span class="cm-punctuation">.</span><span class="cm-property">speechSynthesis</span><span class="cm-punctuation">.</span><span class="cm-property">cancel</span><span class="cm-punctuation">()</span>
<span class="cm-variable">window</span><span class="cm-punctuation">.</span><span class="cm-property">speechSynthesis</span><span class="cm-punctuation">.</span><span class="cm-property">speak</span> <span class="cm-keyword">new</span> <span class="cm-variable">SpeechSynthesisUtterance</span> <span class="cm-variable">text</span>
<span class="cm-variable">countdown</span> <span class="cm-punctuation">=</span> <span class="cm-punctuation">(</span><span class="cm-variable">seconds</span><span class="cm-punctuation">)</span> <span class="cm-operator">-></span>
<span class="cm-keyword">for</span> <span class="cm-variable">i</span> <span class="cm-operator">in</span> <span class="cm-punctuation">[</span><span class="cm-variable">seconds</span><span class="cm-punctuation">..</span><span class="cm-number">1</span><span class="cm-punctuation">]</span>
<span class="cm-variable">say</span> <span class="cm-variable">i</span>
<span class="cm-variable">await</span> <span class="cm-variable">sleep</span> <span class="cm-number">1000</span> <span class="cm-comment"># wait one second</span>
<span class="cm-dedent"> </span><span class="cm-variable">say</span> <span class="cm-string">"Blastoff!"</span>
<span class="cm-variable">countdown</span> <span class="cm-number">3</span>
</pre>
</div>
<div class="col-md-6 javascript-output-column">
<textarea class="javascript-output" id="async-js">// Your browser must support async/await and speech synthesis
// to run this example.
var countdown, say, sleep;
sleep = function(ms) {
return new Promise(function(resolve) {
return window.setTimeout(resolve, ms);
});
};
say = function(text) {
window.speechSynthesis.cancel();
return window.speechSynthesis.speak(new SpeechSynthesisUtterance(text));
};
countdown = async function(seconds) {
var i, j, ref;
for (i = j = ref = seconds; (ref <= 1 ? j <= 1 : j >= 1); i = ref <= 1 ? ++j : --j) {
say(i);
await sleep(1000); // wait one second
}
return say("Blastoff!");
};
countdown(3);
</textarea>
<pre class="placeholder-code"><span class="cm-comment">// Your browser must support async/await and speech synthesis</span>
<span class="cm-comment">// to run this example.</span>
<span class="cm-keyword">var</span> <span class="cm-def">countdown</span>, <span class="cm-def">say</span>, <span class="cm-def">sleep</span>;
<span class="cm-variable">sleep</span> <span class="cm-operator">=</span> <span class="cm-keyword">function</span>(<span class="cm-def">ms</span>) {
<span class="cm-keyword">return</span> <span class="cm-keyword">new</span> <span class="cm-variable">Promise</span>(<span class="cm-keyword">function</span>(<span class="cm-def">resolve</span>) {
<span class="cm-keyword">return</span> <span class="cm-variable">window</span>.<span class="cm-property">setTimeout</span>(<span class="cm-variable-2">resolve</span>, <span class="cm-variable-2">ms</span>);
});
};
<span class="cm-variable">say</span> <span class="cm-operator">=</span> <span class="cm-keyword">function</span>(<span class="cm-def">text</span>) {
<span class="cm-variable">window</span>.<span class="cm-property">speechSynthesis</span>.<span class="cm-property">cancel</span>();
<span class="cm-keyword">return</span> <span class="cm-variable">window</span>.<span class="cm-property">speechSynthesis</span>.<span class="cm-property">speak</span>(<span class="cm-keyword">new</span> <span class="cm-variable">SpeechSynthesisUtterance</span>(<span class="cm-variable-2">text</span>));
};
<span class="cm-variable">countdown</span> <span class="cm-operator">=</span> <span class="cm-keyword">async</span> <span class="cm-keyword">function</span>(<span class="cm-def">seconds</span>) {
<span class="cm-keyword">var</span> <span class="cm-def">i</span>, <span class="cm-def">j</span>, <span class="cm-def">ref</span>;
<span class="cm-keyword">for</span> (<span class="cm-variable-2">i</span> <span class="cm-operator">=</span> <span class="cm-variable-2">j</span> <span class="cm-operator">=</span> <span class="cm-variable-2">ref</span> <span class="cm-operator">=</span> <span class="cm-variable-2">seconds</span>; (<span class="cm-variable-2">ref</span> <span class="cm-operator">&lt;=</span> <span class="cm-number">1</span> <span class="cm-operator">?</span> <span class="cm-variable-2">j</span> <span class="cm-operator">&lt;=</span> <span class="cm-number">1</span> : <span class="cm-variable-2">j</span> <span class="cm-operator">>=</span> <span class="cm-number">1</span>); <span class="cm-variable-2">i</span> <span class="cm-operator">=</span> <span class="cm-variable-2">ref</span> <span class="cm-operator">&lt;=</span> <span class="cm-number">1</span> <span class="cm-operator">?</span> <span class="cm-operator">++</span><span class="cm-variable-2">j</span> : <span class="cm-operator">--</span><span class="cm-variable-2">j</span>) {
<span class="cm-variable">say</span>(<span class="cm-variable-2">i</span>);
<span class="cm-keyword">await</span> <span class="cm-variable">sleep</span>(<span class="cm-number">1000</span>); <span class="cm-comment">// wait one second</span>
}
<span class="cm-keyword">return</span> <span class="cm-variable">say</span>(<span class="cm-string">"Blastoff!"</span>);
};
<span class="cm-variable">countdown</span>(<span class="cm-number">3</span>);
</pre>
</div>
</div>
<div class="row">
<div class="col text-right">
<button type="button" class="btn btn-primary" data-action="run-code-example" data-example="async" data-run="true"><small><svg class="play-button" viewBox="0 0 24 24">
<path d="M2.56-0.01v24.02L21.44 11.98 2.56-0.01z"></path>
</svg>
</small></button>
</div>
</div>
</aside>
</section>
<section id="classes">
<h2>Classes</h2>
<p>CoffeeScript 1 provided the <code>class</code> and <code>extends</code> keywords as syntactic sugar for working with prototypal functions. With ES2015, JavaScript has adopted those keywords; so CoffeeScript 2 compiles its <code>class</code> and <code>extends</code> keywords to ES2015 classes.</p>
<aside class="code-example container-fluid bg-ribbed-dark" data-example="classes">
<div class="row">
<div class="col-md-6 coffeescript-input-column">
<textarea class="coffeescript-input" id="classes-coffee">class Animal
constructor: (@name) ->
move: (meters) ->
alert @name + " moved #{meters}m."
class Snake extends Animal
move: ->
alert "Slithering..."
super 5
class Horse extends Animal
move: ->
alert "Galloping..."
super 45
sam = new Snake "Sammy the Python"
tom = new Horse "Tommy the Palomino"
sam.move()
tom.move()
</textarea>
<pre class="placeholder-code"><span class="cm-keyword">class</span> <span class="cm-variable">Animal</span>
<span class="cm-variable">constructor</span><span class="cm-punctuation">:</span> <span class="cm-punctuation">(</span><span class="cm-property">@name</span><span class="cm-punctuation">)</span> <span class="cm-operator">-></span>
<span class="cm-dedent"> </span><span class="cm-variable">move</span><span class="cm-punctuation">:</span> <span class="cm-punctuation">(</span><span class="cm-variable">meters</span><span class="cm-punctuation">)</span> <span class="cm-operator">-></span>
<span class="cm-variable">alert</span> <span class="cm-property">@name</span> <span class="cm-operator">+</span> <span class="cm-string">" moved #{meters}m."</span>
<span class="cm-keyword">class</span> <span class="cm-variable">Snake</span> <span class="cm-keyword">extends</span> <span class="cm-variable">Animal</span>
<span class="cm-variable">move</span><span class="cm-punctuation">:</span> <span class="cm-operator">-></span>
<span class="cm-variable">alert</span> <span class="cm-string">"Slithering..."</span>
<span class="cm-variable">super</span> <span class="cm-number">5</span>
<span class="cm-keyword">class</span> <span class="cm-variable">Horse</span> <span class="cm-keyword">extends</span> <span class="cm-variable">Animal</span>
<span class="cm-variable">move</span><span class="cm-punctuation">:</span> <span class="cm-operator">-></span>
<span class="cm-variable">alert</span> <span class="cm-string">"Galloping..."</span>
<span class="cm-variable">super</span> <span class="cm-number">45</span>
<span class="cm-variable">sam</span> <span class="cm-punctuation">=</span> <span class="cm-keyword">new</span> <span class="cm-variable">Snake</span> <span class="cm-string">"Sammy the Python"</span>
<span class="cm-variable">tom</span> <span class="cm-punctuation">=</span> <span class="cm-keyword">new</span> <span class="cm-variable">Horse</span> <span class="cm-string">"Tommy the Palomino"</span>
<span class="cm-variable">sam</span><span class="cm-punctuation">.</span><span class="cm-property">move</span><span class="cm-punctuation">()</span>
<span class="cm-variable">tom</span><span class="cm-punctuation">.</span><span class="cm-property">move</span><span class="cm-punctuation">()</span>
</pre>
</div>
<div class="col-md-6 javascript-output-column">
<textarea class="javascript-output" id="classes-js">var Animal, Horse, Snake, sam, tom;
Animal = class Animal {
constructor(name) {
this.name = name;
}
move(meters) {
return alert(this.name + ` moved ${meters}m.`);
}
};
Snake = class Snake extends Animal {
move() {
alert("Slithering...");
return super.move(5);
}
};
Horse = class Horse extends Animal {
move() {
alert("Galloping...");
return super.move(45);
}
};
sam = new Snake("Sammy the Python");
tom = new Horse("Tommy the Palomino");
sam.move();
tom.move();
</textarea>
<pre class="placeholder-code"><span class="cm-keyword">var</span> <span class="cm-def">Animal</span>, <span class="cm-def">Horse</span>, <span class="cm-def">Snake</span>, <span class="cm-def">sam</span>, <span class="cm-def">tom</span>;
<span class="cm-variable">Animal</span> <span class="cm-operator">=</span> <span class="cm-keyword">class</span> <span class="cm-def">Animal</span> {
<span class="cm-property">constructor</span>(<span class="cm-def">name</span>) {
<span class="cm-keyword">this</span>.<span class="cm-property">name</span> <span class="cm-operator">=</span> <span class="cm-variable-2">name</span>;
}
<span class="cm-property">move</span>(<span class="cm-def">meters</span>) {
<span class="cm-keyword">return</span> <span class="cm-variable">alert</span>(<span class="cm-keyword">this</span>.<span class="cm-property">name</span> <span class="cm-operator">+</span> <span class="cm-string-2">` moved ${</span><span class="cm-variable-2">meters</span><span class="cm-string-2">}m.`</span>);
}
};
<span class="cm-variable">Snake</span> <span class="cm-operator">=</span> <span class="cm-keyword">class</span> <span class="cm-def">Snake</span> <span class="cm-keyword">extends</span> <span class="cm-variable">Animal</span> {
<span class="cm-property">move</span>() {
<span class="cm-variable">alert</span>(<span class="cm-string">"Slithering..."</span>);
<span class="cm-keyword">return</span> <span class="cm-keyword">super</span>.<span class="cm-property">move</span>(<span class="cm-number">5</span>);
}
};
<span class="cm-variable">Horse</span> <span class="cm-operator">=</span> <span class="cm-keyword">class</span> <span class="cm-def">Horse</span> <span class="cm-keyword">extends</span> <span class="cm-variable">Animal</span> {
<span class="cm-property">move</span>() {
<span class="cm-variable">alert</span>(<span class="cm-string">"Galloping..."</span>);
<span class="cm-keyword">return</span> <span class="cm-keyword">super</span>.<span class="cm-property">move</span>(<span class="cm-number">45</span>);
}
};
<span class="cm-variable">sam</span> <span class="cm-operator">=</span> <span class="cm-keyword">new</span> <span class="cm-variable">Snake</span>(<span class="cm-string">"Sammy the Python"</span>);
<span class="cm-variable">tom</span> <span class="cm-operator">=</span> <span class="cm-keyword">new</span> <span class="cm-variable">Horse</span>(<span class="cm-string">"Tommy the Palomino"</span>);
<span class="cm-variable">sam</span>.<span class="cm-property">move</span>();
<span class="cm-variable">tom</span>.<span class="cm-property">move</span>();
</pre>
</div>
</div>
<div class="row">
<div class="col text-right">
<button type="button" class="btn btn-primary" data-action="run-code-example" data-example="classes" data-run="true"><small><svg class="play-button" viewBox="0 0 24 24">
<path d="M2.56-0.01v24.02L21.44 11.98 2.56-0.01z"></path>
</svg>
</small></button>
</div>
</div>
</aside>
<p>Static methods can be defined using <code>@</code> before the method name:</p>
<aside class="code-example container-fluid bg-ribbed-dark" data-example="static">
<div class="row">
<div class="col-md-6 coffeescript-input-column">
<textarea class="coffeescript-input" id="static-coffee">class Teenager
@say: (speech) ->
words = speech.split ' '
fillers = ['uh', 'um', 'like', 'actually', 'so', 'maybe']
output = []
for word, index in words
output.push word
output.push fillers[Math.floor(Math.random() * fillers.length)] unless index is words.length - 1
output.join ', '
</textarea>
<pre class="placeholder-code"><span class="cm-keyword">class</span> <span class="cm-variable">Teenager</span>
<span class="cm-property">@say</span><span class="cm-punctuation">:</span> <span class="cm-punctuation">(</span><span class="cm-variable">speech</span><span class="cm-punctuation">)</span> <span class="cm-operator">-></span>
<span class="cm-variable">words</span> <span class="cm-punctuation">=</span> <span class="cm-variable">speech</span><span class="cm-punctuation">.</span><span class="cm-property">split</span> <span class="cm-string">' '</span>
<span class="cm-variable">fillers</span> <span class="cm-punctuation">=</span> <span class="cm-punctuation">[</span><span class="cm-string">'uh'</span><span class="cm-punctuation">,</span> <span class="cm-string">'um'</span><span class="cm-punctuation">,</span> <span class="cm-string">'like'</span><span class="cm-punctuation">,</span> <span class="cm-string">'actually'</span><span class="cm-punctuation">,</span> <span class="cm-string">'so'</span><span class="cm-punctuation">,</span> <span class="cm-string">'maybe'</span><span class="cm-punctuation">]</span>
<span class="cm-variable">output</span> <span class="cm-punctuation">=</span> <span class="cm-punctuation">[]</span>
<span class="cm-keyword">for</span> <span class="cm-variable">word</span><span class="cm-punctuation">,</span> <span class="cm-variable">index</span> <span class="cm-operator">in</span> <span class="cm-variable">words</span>
<span class="cm-variable">output</span><span class="cm-punctuation">.</span><span class="cm-property">push</span> <span class="cm-variable">word</span>
<span class="cm-variable">output</span><span class="cm-punctuation">.</span><span class="cm-property">push</span> <span class="cm-variable">fillers</span><span class="cm-punctuation">[</span><span class="cm-variable">Math</span><span class="cm-punctuation">.</span><span class="cm-property">floor</span><span class="cm-punctuation">(</span><span class="cm-variable">Math</span><span class="cm-punctuation">.</span><span class="cm-property">random</span><span class="cm-punctuation">()</span> <span class="cm-operator">*</span> <span class="cm-variable">fillers</span><span class="cm-punctuation">.</span><span class="cm-property">length</span><span class="cm-punctuation">)]</span> <span class="cm-keyword">unless</span> <span class="cm-variable">index</span> <span class="cm-operator">is</span> <span class="cm-variable">words</span><span class="cm-punctuation">.</span><span class="cm-property">length</span> <span class="cm-operator">-</span> <span class="cm-number">1</span>
<span class="cm-dedent"> </span><span class="cm-variable">output</span><span class="cm-punctuation">.</span><span class="cm-property">join</span> <span class="cm-string">', '</span>
</pre>
</div>
<div class="col-md-6 javascript-output-column">
<textarea class="javascript-output" id="static-js">var Teenager;
Teenager = class Teenager {
static say(speech) {
var fillers, i, index, len, output, word, words;
words = speech.split(' ');
fillers = ['uh', 'um', 'like', 'actually', 'so', 'maybe'];
output = [];
for (index = i = 0, len = words.length; i < len; index = ++i) {
word = words[index];
output.push(word);
if (index !== words.length - 1) {
output.push(fillers[Math.floor(Math.random() * fillers.length)]);
}
}
return output.join(', ');
}
};
</textarea>
<pre class="placeholder-code"><span class="cm-keyword">var</span> <span class="cm-def">Teenager</span>;
<span class="cm-variable">Teenager</span> <span class="cm-operator">=</span> <span class="cm-keyword">class</span> <span class="cm-def">Teenager</span> {
<span class="cm-keyword">static</span> <span class="cm-property">say</span>(<span class="cm-def">speech</span>) {
<span class="cm-keyword">var</span> <span class="cm-def">fillers</span>, <span class="cm-def">i</span>, <span class="cm-def">index</span>, <span class="cm-def">len</span>, <span class="cm-def">output</span>, <span class="cm-def">word</span>, <span class="cm-def">words</span>;
<span class="cm-variable-2">words</span> <span class="cm-operator">=</span> <span class="cm-variable-2">speech</span>.<span class="cm-property">split</span>(<span class="cm-string">' '</span>);
<span class="cm-variable-2">fillers</span> <span class="cm-operator">=</span> [<span class="cm-string">'uh'</span>, <span class="cm-string">'um'</span>, <span class="cm-string">'like'</span>, <span class="cm-string">'actually'</span>, <span class="cm-string">'so'</span>, <span class="cm-string">'maybe'</span>];
<span class="cm-variable-2">output</span> <span class="cm-operator">=</span> [];
<span class="cm-keyword">for</span> (<span class="cm-variable-2">index</span> <span class="cm-operator">=</span> <span class="cm-variable-2">i</span> <span class="cm-operator">=</span> <span class="cm-number">0</span>, <span class="cm-variable-2">len</span> <span class="cm-operator">=</span> <span class="cm-variable-2">words</span>.<span class="cm-property">length</span>; <span class="cm-variable-2">i</span> <span class="cm-operator">&lt;</span> <span class="cm-variable-2">len</span>; <span class="cm-variable-2">index</span> <span class="cm-operator">=</span> <span class="cm-operator">++</span><span class="cm-variable-2">i</span>) {
<span class="cm-variable-2">word</span> <span class="cm-operator">=</span> <span class="cm-variable-2">words</span>[<span class="cm-variable-2">index</span>];
<span class="cm-variable-2">output</span>.<span class="cm-property">push</span>(<span class="cm-variable-2">word</span>);
<span class="cm-keyword">if</span> (<span class="cm-variable-2">index</span> <span class="cm-operator">!==</span> <span class="cm-variable-2">words</span>.<span class="cm-property">length</span> <span class="cm-operator">-</span> <span class="cm-number">1</span>) {
<span class="cm-variable-2">output</span>.<span class="cm-property">push</span>(<span class="cm-variable-2">fillers</span>[<span class="cm-variable">Math</span>.<span class="cm-property">floor</span>(<span class="cm-variable">Math</span>.<span class="cm-property">random</span>() <span class="cm-operator">*</span> <span class="cm-variable-2">fillers</span>.<span class="cm-property">length</span>)]);
}
}
<span class="cm-keyword">return</span> <span class="cm-variable-2">output</span>.<span class="cm-property">join</span>(<span class="cm-string">', '</span>);
}
};
</pre>
</div>
</div>
<div class="row">
<div class="col text-right">
<button type="button" class="btn btn-primary" data-action="run-code-example" data-example="static" data-run="Teenager.say%28%22Are%20we%20there%20yet%3F%22%29"><small><svg class="play-button" viewBox="0 0 24 24">
<path d="M2.56-0.01v24.02L21.44 11.98 2.56-0.01z"></path>
</svg>
</small>Teenager.say(&quot;Are we there yet?&quot;)</button>
</div>
</div>
</aside>
<p>Finally, class definitions are blocks of executable code, which make for interesting metaprogramming possibilities. In the context of a class definition, <code>this</code> is the class object itself; therefore, you can assign static properties by using <code>@property: value</code>.</p>
</section>
<section id="prototypal-inheritance">
<h2>Prototypal Inheritance</h2>
<p>In addition to supporting ES2015 classes, CoffeeScript provides a shortcut for working with prototypes. The <code>::</code> operator gives you quick access to an objects prototype:</p>
<aside class="code-example container-fluid bg-ribbed-dark" data-example="prototypes">
<div class="row">
<div class="col-md-6 coffeescript-input-column">
<textarea class="coffeescript-input" id="prototypes-coffee">String::dasherize = ->
this.replace /_/g, "-"
</textarea>
<pre class="placeholder-code"><span class="cm-variable">String</span><span class="cm-punctuation">::</span><span class="cm-variable">dasherize</span> <span class="cm-punctuation">=</span> <span class="cm-operator">-></span>
<span class="cm-keyword">this</span><span class="cm-punctuation">.</span><span class="cm-property">replace</span> <span class="cm-string-2">/_/</span><span class="cm-variable">g</span><span class="cm-punctuation">,</span> <span class="cm-string">"-"</span>
</pre>
</div>
<div class="col-md-6 javascript-output-column">
<textarea class="javascript-output" id="prototypes-js">String.prototype.dasherize = function() {
return this.replace(/_/g, "-");
};
</textarea>
<pre class="placeholder-code"><span class="cm-variable">String</span>.<span class="cm-property">prototype</span>.<span class="cm-property">dasherize</span> <span class="cm-operator">=</span> <span class="cm-keyword">function</span>() {
<span class="cm-keyword">return</span> <span class="cm-keyword">this</span>.<span class="cm-property">replace</span>(<span class="cm-string-2">/_/g</span>, <span class="cm-string">"-"</span>);
};
</pre>
</div>
</div>
<div class="row">
<div class="col text-right">
<button type="button" class="btn btn-primary" data-action="run-code-example" data-example="prototypes" data-run="%22one_two%22.dasherize%28%29"><small><svg class="play-button" viewBox="0 0 24 24">
<path d="M2.56-0.01v24.02L21.44 11.98 2.56-0.01z"></path>
</svg>
</small>&quot;one_two&quot;.dasherize()</button>
</div>
</div>
</aside>
</section>
<section id="switch">
<h2>Switch/When/Else</h2>
<p><code>switch</code> statements in JavaScript are a bit awkward. You need to remember to <code>break</code> at the end of every <code>case</code> statement to avoid accidentally falling through to the default case. CoffeeScript prevents accidental fall-through, and can convert the <code>switch</code> into a returnable, assignable expression. The format is: <code>switch</code> condition, <code>when</code> clauses, <code>else</code> the default case.</p>
<p>As in Ruby, <code>switch</code> statements in CoffeeScript can take multiple values for each <code>when</code> clause. If any of the values match, the clause runs.</p>
<aside class="code-example container-fluid bg-ribbed-dark" data-example="switch">
<div class="row">
<div class="col-md-6 coffeescript-input-column">
<textarea class="coffeescript-input" id="switch-coffee">switch day
when "Mon" then go work
when "Tue" then go relax
when "Thu" then go iceFishing
when "Fri", "Sat"
if day is bingoDay
go bingo
go dancing
when "Sun" then go church
else go work
</textarea>
<pre class="placeholder-code"><span class="cm-keyword">switch</span> <span class="cm-variable">day</span>
<span class="cm-keyword">when</span> <span class="cm-string">"Mon"</span> <span class="cm-keyword">then</span> <span class="cm-variable">go</span> <span class="cm-variable">work</span>
<span class="cm-keyword">when</span> <span class="cm-string">"Tue"</span> <span class="cm-keyword">then</span> <span class="cm-variable">go</span> <span class="cm-variable">relax</span>
<span class="cm-keyword">when</span> <span class="cm-string">"Thu"</span> <span class="cm-keyword">then</span> <span class="cm-variable">go</span> <span class="cm-variable">iceFishing</span>
<span class="cm-keyword">when</span> <span class="cm-string">"Fri"</span><span class="cm-punctuation">,</span> <span class="cm-string">"Sat"</span>
<span class="cm-indent"> </span><span class="cm-keyword">if</span> <span class="cm-variable">day</span> <span class="cm-operator">is</span> <span class="cm-variable">bingoDay</span>
<span class="cm-variable">go</span> <span class="cm-variable">bingo</span>
<span class="cm-variable">go</span> <span class="cm-variable">dancing</span>
<span class="cm-dedent"> </span><span class="cm-keyword">when</span> <span class="cm-string">"Sun"</span> <span class="cm-keyword">then</span> <span class="cm-variable">go</span> <span class="cm-variable">church</span>
<span class="cm-keyword">else</span> <span class="cm-variable">go</span> <span class="cm-variable">work</span>
</pre>
</div>
<div class="col-md-6 javascript-output-column">
<textarea class="javascript-output" id="switch-js">switch (day) {
case "Mon":
go(work);
break;
case "Tue":
go(relax);
break;
case "Thu":
go(iceFishing);
break;
case "Fri":
case "Sat":
if (day === bingoDay) {
go(bingo);
go(dancing);
}
break;
case "Sun":
go(church);
break;
default:
go(work);
}
</textarea>
<pre class="placeholder-code"><span class="cm-keyword">switch</span> (<span class="cm-variable">day</span>) {
<span class="cm-keyword">case</span> <span class="cm-string">"Mon"</span>:
<span class="cm-variable">go</span>(<span class="cm-variable">work</span>);
<span class="cm-keyword">break</span>;
<span class="cm-keyword">case</span> <span class="cm-string">"Tue"</span>:
<span class="cm-variable">go</span>(<span class="cm-variable">relax</span>);
<span class="cm-keyword">break</span>;
<span class="cm-keyword">case</span> <span class="cm-string">"Thu"</span>:
<span class="cm-variable">go</span>(<span class="cm-variable">iceFishing</span>);
<span class="cm-keyword">break</span>;
<span class="cm-keyword">case</span> <span class="cm-string">"Fri"</span>:
<span class="cm-keyword">case</span> <span class="cm-string">"Sat"</span>:
<span class="cm-keyword">if</span> (<span class="cm-variable">day</span> <span class="cm-operator">===</span> <span class="cm-variable">bingoDay</span>) {
<span class="cm-variable">go</span>(<span class="cm-variable">bingo</span>);
<span class="cm-variable">go</span>(<span class="cm-variable">dancing</span>);
}
<span class="cm-keyword">break</span>;
<span class="cm-keyword">case</span> <span class="cm-string">"Sun"</span>:
<span class="cm-variable">go</span>(<span class="cm-variable">church</span>);
<span class="cm-keyword">break</span>;
<span class="cm-keyword">default</span>:
<span class="cm-variable">go</span>(<span class="cm-variable">work</span>);
}
</pre>
</div>
</div>
</aside>
<p><code>switch</code> statements can also be used without a control expression, turning them in to a cleaner alternative to <code>if</code>/<code>else</code> chains.</p>
<aside class="code-example container-fluid bg-ribbed-dark" data-example="switch_with_no_expression">
<div class="row">
<div class="col-md-6 coffeescript-input-column">
<textarea class="coffeescript-input" id="switch_with_no_expression-coffee">score = 76
grade = switch
when score < 60 then 'F'
when score < 70 then 'D'
when score < 80 then 'C'
when score < 90 then 'B'
else 'A'
# grade == 'C'
</textarea>
<pre class="placeholder-code"><span class="cm-variable">score</span> <span class="cm-punctuation">=</span> <span class="cm-number">76</span>
<span class="cm-variable">grade</span> <span class="cm-punctuation">=</span> <span class="cm-keyword">switch</span>
<span class="cm-keyword">when</span> <span class="cm-variable">score</span> <span class="cm-operator">&lt;</span> <span class="cm-number">60</span> <span class="cm-keyword">then</span> <span class="cm-string">'F'</span>
<span class="cm-keyword">when</span> <span class="cm-variable">score</span> <span class="cm-operator">&lt;</span> <span class="cm-number">70</span> <span class="cm-keyword">then</span> <span class="cm-string">'D'</span>
<span class="cm-keyword">when</span> <span class="cm-variable">score</span> <span class="cm-operator">&lt;</span> <span class="cm-number">80</span> <span class="cm-keyword">then</span> <span class="cm-string">'C'</span>
<span class="cm-keyword">when</span> <span class="cm-variable">score</span> <span class="cm-operator">&lt;</span> <span class="cm-number">90</span> <span class="cm-keyword">then</span> <span class="cm-string">'B'</span>
<span class="cm-keyword">else</span> <span class="cm-string">'A'</span>
<span class="cm-comment"># grade == 'C'</span>
</pre>
</div>
<div class="col-md-6 javascript-output-column">
<textarea class="javascript-output" id="switch_with_no_expression-js">var grade, score;
score = 76;
grade = (function() {
switch (false) {
case !(score < 60):
return 'F';
case !(score < 70):
return 'D';
case !(score < 80):
return 'C';
case !(score < 90):
return 'B';
default:
return 'A';
}
})();
// grade == 'C'
</textarea>
<pre class="placeholder-code"><span class="cm-keyword">var</span> <span class="cm-def">grade</span>, <span class="cm-def">score</span>;
<span class="cm-variable">score</span> <span class="cm-operator">=</span> <span class="cm-number">76</span>;
<span class="cm-variable">grade</span> <span class="cm-operator">=</span> (<span class="cm-keyword">function</span>() {
<span class="cm-keyword">switch</span> (<span class="cm-atom">false</span>) {
<span class="cm-keyword">case</span> <span class="cm-operator">!</span>(<span class="cm-variable">score</span> <span class="cm-operator">&lt;</span> <span class="cm-number">60</span>):
<span class="cm-keyword">return</span> <span class="cm-string">'F'</span>;
<span class="cm-keyword">case</span> <span class="cm-operator">!</span>(<span class="cm-variable">score</span> <span class="cm-operator">&lt;</span> <span class="cm-number">70</span>):
<span class="cm-keyword">return</span> <span class="cm-string">'D'</span>;
<span class="cm-keyword">case</span> <span class="cm-operator">!</span>(<span class="cm-variable">score</span> <span class="cm-operator">&lt;</span> <span class="cm-number">80</span>):
<span class="cm-keyword">return</span> <span class="cm-string">'C'</span>;
<span class="cm-keyword">case</span> <span class="cm-operator">!</span>(<span class="cm-variable">score</span> <span class="cm-operator">&lt;</span> <span class="cm-number">90</span>):
<span class="cm-keyword">return</span> <span class="cm-string">'B'</span>;
<span class="cm-keyword">default</span>:
<span class="cm-keyword">return</span> <span class="cm-string">'A'</span>;
}
})();
<span class="cm-comment">// grade == 'C'</span>
</pre>
</div>
</div>
</aside>
</section>
<section id="try">
<h2>Try/Catch/Finally</h2>
<p><code>try</code> expressions have the same semantics as <code>try</code> statements in JavaScript, though in CoffeeScript, you may omit <em>both</em> the catch and finally parts. The catch part may also omit the error parameter if it is not needed.</p>
<aside class="code-example container-fluid bg-ribbed-dark" data-example="try">
<div class="row">
<div class="col-md-6 coffeescript-input-column">
<textarea class="coffeescript-input" id="try-coffee">try
allHellBreaksLoose()
catsAndDogsLivingTogether()
catch error
print error
finally
cleanUp()
</textarea>
<pre class="placeholder-code"><span class="cm-keyword">try</span>
<span class="cm-variable">allHellBreaksLoose</span><span class="cm-punctuation">()</span>
<span class="cm-variable">catsAndDogsLivingTogether</span><span class="cm-punctuation">()</span>
<span class="cm-keyword">catch</span> <span class="cm-variable">error</span>
<span class="cm-variable">print</span> <span class="cm-variable">error</span>
<span class="cm-keyword">finally</span>
<span class="cm-variable">cleanUp</span><span class="cm-punctuation">()</span>
</pre>
</div>
<div class="col-md-6 javascript-output-column">
<textarea class="javascript-output" id="try-js">var error;
try {
allHellBreaksLoose();
catsAndDogsLivingTogether();
} catch (error1) {
error = error1;
print(error);
} finally {
cleanUp();
}
</textarea>
<pre class="placeholder-code"><span class="cm-keyword">var</span> <span class="cm-def">error</span>;
<span class="cm-keyword">try</span> {
<span class="cm-variable">allHellBreaksLoose</span>();
<span class="cm-variable">catsAndDogsLivingTogether</span>();
} <span class="cm-keyword">catch</span> (<span class="cm-def">error1</span>) {
<span class="cm-variable">error</span> <span class="cm-operator">=</span> <span class="cm-variable-2">error1</span>;
<span class="cm-variable">print</span>(<span class="cm-variable">error</span>);
} <span class="cm-keyword">finally</span> {
<span class="cm-variable">cleanUp</span>();
}
</pre>
</div>
</div>
</aside>
</section>
<section id="comparisons">
<h2>Chained Comparisons</h2>
<p>CoffeeScript borrows <a href="https://docs.python.org/3/reference/expressions.html#not-in">chained comparisons</a> from Python — making it easy to test if a value falls within a certain range.</p>
<aside class="code-example container-fluid bg-ribbed-dark" data-example="comparisons">
<div class="row">
<div class="col-md-6 coffeescript-input-column">
<textarea class="coffeescript-input" id="comparisons-coffee">cholesterol = 127
healthy = 200 > cholesterol > 60
</textarea>
<pre class="placeholder-code"><span class="cm-variable">cholesterol</span> <span class="cm-punctuation">=</span> <span class="cm-number">127</span>
<span class="cm-variable">healthy</span> <span class="cm-punctuation">=</span> <span class="cm-number">200</span> <span class="cm-operator">></span> <span class="cm-variable">cholesterol</span> <span class="cm-operator">></span> <span class="cm-number">60</span>
</pre>
</div>
<div class="col-md-6 javascript-output-column">
<textarea class="javascript-output" id="comparisons-js">var cholesterol, healthy;
cholesterol = 127;
healthy = (200 > cholesterol && cholesterol > 60);
</textarea>
<pre class="placeholder-code"><span class="cm-keyword">var</span> <span class="cm-def">cholesterol</span>, <span class="cm-def">healthy</span>;
<span class="cm-variable">cholesterol</span> <span class="cm-operator">=</span> <span class="cm-number">127</span>;
<span class="cm-variable">healthy</span> <span class="cm-operator">=</span> (<span class="cm-number">200</span> <span class="cm-operator">></span> <span class="cm-variable">cholesterol</span> <span class="cm-operator">&amp;&amp;</span> <span class="cm-variable">cholesterol</span> <span class="cm-operator">></span> <span class="cm-number">60</span>);
</pre>
</div>
</div>
<div class="row">
<div class="col text-right">
<button type="button" class="btn btn-primary" data-action="run-code-example" data-example="comparisons" data-run="healthy"><small><svg class="play-button" viewBox="0 0 24 24">
<path d="M2.56-0.01v24.02L21.44 11.98 2.56-0.01z"></path>
</svg>
</small>healthy</button>
</div>
</div>
</aside>
</section>
<section id="regexes">
<h2>Block Regular Expressions</h2>
<p>Similar to block strings and comments, CoffeeScript supports block regexes — extended regular expressions that ignore internal whitespace and can contain comments and interpolation. Modeled after Perls <code>/x</code> modifier, CoffeeScripts block regexes are delimited by <code>///</code> and go a long way towards making complex regular expressions readable. To quote from the CoffeeScript source:</p>
<aside class="code-example container-fluid bg-ribbed-dark" data-example="heregexes">
<div class="row">
<div class="col-md-6 coffeescript-input-column">
<textarea class="coffeescript-input" id="heregexes-coffee">NUMBER = ///
^ 0b[01]+ | # binary
^ 0o[0-7]+ | # octal
^ 0x[\da-f]+ | # hex
^ \d*\.?\d+ (?:e[+-]?\d+)? # decimal
///i
</textarea>
<pre class="placeholder-code"><span class="cm-variable">NUMBER</span> <span class="cm-punctuation">=</span> <span class="cm-string-2">///</span>
<span class="cm-indent"> </span><span class="cm-operator">^</span> <span class="cm-number">0</span><span class="cm-variable">b</span><span class="cm-punctuation">[</span><span class="cm-error">0</span><span class="cm-number">1</span><span class="cm-punctuation">]</span><span class="cm-operator">+</span> <span class="cm-operator">|</span> <span class="cm-comment"># binary</span>
<span class="cm-operator">^</span> <span class="cm-number">0</span><span class="cm-variable">o</span><span class="cm-punctuation">[</span><span class="cm-number">0-7</span><span class="cm-punctuation">]</span><span class="cm-operator">+</span> <span class="cm-operator">|</span> <span class="cm-comment"># octal</span>
<span class="cm-operator">^</span> <span class="cm-error">0</span><span class="cm-variable">x</span><span class="cm-punctuation">[</span><span class="cm-error">\</span><span class="cm-variable">da</span><span class="cm-operator">-</span><span class="cm-variable">f</span><span class="cm-punctuation">]</span><span class="cm-operator">+</span> <span class="cm-operator">|</span> <span class="cm-comment"># hex</span>
<span class="cm-operator">^</span> <span class="cm-error">\</span><span class="cm-variable">d</span><span class="cm-operator">*</span><span class="cm-error">\</span><span class="cm-punctuation">.</span><span class="cm-operator">?</span><span class="cm-error">\</span><span class="cm-variable">d</span><span class="cm-operator">+</span> <span class="cm-punctuation">(</span><span class="cm-operator">?</span><span class="cm-punctuation">:</span><span class="cm-variable">e</span><span class="cm-punctuation">[</span><span class="cm-operator">+-</span><span class="cm-punctuation">]</span><span class="cm-operator">?</span><span class="cm-error">\</span><span class="cm-variable">d</span><span class="cm-operator">+</span><span class="cm-punctuation">)</span><span class="cm-operator">?</span> <span class="cm-comment"># decimal</span>
<span class="cm-string-2">///i</span>
</pre>
</div>
<div class="col-md-6 javascript-output-column">
<textarea class="javascript-output" id="heregexes-js">var NUMBER;
NUMBER = /^0b[01]+|^0o[0-7]+|^0x[\da-f]+|^\d*\.?\d+(?:e[+-]?\d+)?/i; // binary
// octal
// hex
// decimal
</textarea>
<pre class="placeholder-code"><span class="cm-keyword">var</span> <span class="cm-def">NUMBER</span>;
<span class="cm-variable">NUMBER</span> <span class="cm-operator">=</span> <span class="cm-string-2">/^0b[01]+|^0o[0-7]+|^0x[\da-f]+|^\d*\.?\d+(?:e[+-]?\d+)?/i</span>; <span class="cm-comment">// binary</span>
<span class="cm-comment">// octal</span>
<span class="cm-comment">// hex</span>
<span class="cm-comment">// decimal</span>
</pre>
</div>
</div>
</aside>
</section>
<section id="tagged-template-literals">
<h2>Tagged Template Literals</h2>
<p>CoffeeScript supports <a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Template_literals#Tagged_template_literals">ES2015 tagged template literals</a>, which enable customized string interpolation. If you immediately prefix a string with a function name (no space between the two), CoffeeScript will output this “function plus string” combination as an ES2015 tagged template literal, which will <a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Template_literals#Tagged_template_literals">behave accordingly</a>: the function is called, with the parameters being the input text and expression parts that make up the interpolated string. The function can then assemble these parts into an output string, providing custom string interpolation.</p>
<aside class="code-example container-fluid bg-ribbed-dark" data-example="tagged_template_literals">
<div class="row">
<div class="col-md-6 coffeescript-input-column">
<textarea class="coffeescript-input" id="tagged_template_literals-coffee">upperCaseExpr = (textParts, expressions...) ->
textParts.reduce (text, textPart, i) ->
text + expressions[i - 1].toUpperCase() + textPart
greet = (name, adjective) ->
upperCaseExpr"""
Hi #{name}. You look #{adjective}!
"""
</textarea>
<pre class="placeholder-code"><span class="cm-variable">upperCaseExpr</span> <span class="cm-punctuation">=</span> <span class="cm-punctuation">(</span><span class="cm-variable">textParts</span><span class="cm-punctuation">,</span> <span class="cm-variable">expressions</span><span class="cm-punctuation">...)</span> <span class="cm-operator">-></span>
<span class="cm-variable">textParts</span><span class="cm-punctuation">.</span><span class="cm-property">reduce</span> <span class="cm-punctuation">(</span><span class="cm-variable">text</span><span class="cm-punctuation">,</span> <span class="cm-variable">textPart</span><span class="cm-punctuation">,</span> <span class="cm-variable">i</span><span class="cm-punctuation">)</span> <span class="cm-operator">-></span>
<span class="cm-variable">text</span> <span class="cm-operator">+</span> <span class="cm-variable">expressions</span><span class="cm-punctuation">[</span><span class="cm-variable">i</span> <span class="cm-operator">-</span> <span class="cm-number">1</span><span class="cm-punctuation">].</span><span class="cm-property">toUpperCase</span><span class="cm-punctuation">()</span> <span class="cm-operator">+</span> <span class="cm-variable">textPart</span>
<span class="cm-variable">greet</span> <span class="cm-punctuation">=</span> <span class="cm-punctuation">(</span><span class="cm-variable">name</span><span class="cm-punctuation">,</span> <span class="cm-variable">adjective</span><span class="cm-punctuation">)</span> <span class="cm-operator">-></span>
<span class="cm-variable">upperCaseExpr</span><span class="cm-string">"""</span>
<span class="cm-string"> Hi #{name}. You look #{adjective}!</span>
<span class="cm-string"> """</span>
</pre>
</div>
<div class="col-md-6 javascript-output-column">
<textarea class="javascript-output" id="tagged_template_literals-js">var greet, upperCaseExpr;
upperCaseExpr = function(textParts, ...expressions) {
return textParts.reduce(function(text, textPart, i) {
return text + expressions[i - 1].toUpperCase() + textPart;
});
};
greet = function(name, adjective) {
return upperCaseExpr`Hi ${name}. You look ${adjective}!`;
};
</textarea>
<pre class="placeholder-code"><span class="cm-keyword">var</span> <span class="cm-def">greet</span>, <span class="cm-def">upperCaseExpr</span>;
<span class="cm-variable">upperCaseExpr</span> <span class="cm-operator">=</span> <span class="cm-keyword">function</span>(<span class="cm-def">textParts</span>, <span class="cm-meta">...</span><span class="cm-def">expressions</span>) {
<span class="cm-keyword">return</span> <span class="cm-variable-2">textParts</span>.<span class="cm-property">reduce</span>(<span class="cm-keyword">function</span>(<span class="cm-def">text</span>, <span class="cm-def">textPart</span>, <span class="cm-def">i</span>) {
<span class="cm-keyword">return</span> <span class="cm-variable-2">text</span> <span class="cm-operator">+</span> <span class="cm-variable-2">expressions</span>[<span class="cm-variable-2">i</span> <span class="cm-operator">-</span> <span class="cm-number">1</span>].<span class="cm-property">toUpperCase</span>() <span class="cm-operator">+</span> <span class="cm-variable-2">textPart</span>;
});
};
<span class="cm-variable">greet</span> <span class="cm-operator">=</span> <span class="cm-keyword">function</span>(<span class="cm-def">name</span>, <span class="cm-def">adjective</span>) {
<span class="cm-keyword">return</span> <span class="cm-variable">upperCaseExpr</span><span class="cm-string-2">`Hi ${</span><span class="cm-variable-2">name</span><span class="cm-string-2">}. You look ${</span><span class="cm-variable-2">adjective</span><span class="cm-string-2">}!`</span>;
};
</pre>
</div>
</div>
<div class="row">
<div class="col text-right">
<button type="button" class="btn btn-primary" data-action="run-code-example" data-example="tagged_template_literals" data-run="greet%28%22greg%22%2C%20%22awesome%22%29"><small><svg class="play-button" viewBox="0 0 24 24">
<path d="M2.56-0.01v24.02L21.44 11.98 2.56-0.01z"></path>
</svg>
</small>greet(&quot;greg&quot;, &quot;awesome&quot;)</button>
</div>
</div>
</aside>
</section>
<section id="modules">
<h2>Modules</h2>
<p>ES2015 modules are supported in CoffeeScript, with very similar <code>import</code> and <code>export</code> syntax:</p>
<aside class="code-example container-fluid bg-ribbed-dark" data-example="modules">
<div class="row">
<div class="col-md-6 coffeescript-input-column">
<textarea class="coffeescript-input" id="modules-coffee">import 'local-file.coffee'
import 'coffeescript'
import _ from 'underscore'
import * as underscore from 'underscore'
import { now } from 'underscore'
import { now as currentTimestamp } from 'underscore'
import { first, last } from 'underscore'
import utilityBelt, { each } from 'underscore'
export default Math
export square = (x) -> x * x
export class Mathematics
least: (x, y) -> if x < y then x else y
export { sqrt }
export { sqrt as squareRoot }
export { Mathematics as default, sqrt as squareRoot }
export * from 'underscore'
export { max, min } from 'underscore'
</textarea>
<pre class="placeholder-code"><span class="cm-variable">import</span> <span class="cm-string">'local-file.coffee'</span>
<span class="cm-variable">import</span> <span class="cm-string">'coffeescript'</span>
<span class="cm-variable">import</span> <span class="cm-variable">_</span> <span class="cm-variable">from</span> <span class="cm-string">'underscore'</span>
<span class="cm-variable">import</span> <span class="cm-operator">*</span> <span class="cm-variable">as</span> <span class="cm-variable">underscore</span> <span class="cm-variable">from</span> <span class="cm-string">'underscore'</span>
<span class="cm-variable">import</span> <span class="cm-punctuation">{</span> <span class="cm-variable">now</span> <span class="cm-punctuation">}</span> <span class="cm-variable">from</span> <span class="cm-string">'underscore'</span>
<span class="cm-variable">import</span> <span class="cm-punctuation">{</span> <span class="cm-variable">now</span> <span class="cm-variable">as</span> <span class="cm-variable">currentTimestamp</span> <span class="cm-punctuation">}</span> <span class="cm-variable">from</span> <span class="cm-string">'underscore'</span>
<span class="cm-variable">import</span> <span class="cm-punctuation">{</span> <span class="cm-variable">first</span><span class="cm-punctuation">,</span> <span class="cm-variable">last</span> <span class="cm-punctuation">}</span> <span class="cm-variable">from</span> <span class="cm-string">'underscore'</span>
<span class="cm-variable">import</span> <span class="cm-variable">utilityBelt</span><span class="cm-punctuation">,</span> <span class="cm-punctuation">{</span> <span class="cm-variable">each</span> <span class="cm-punctuation">}</span> <span class="cm-variable">from</span> <span class="cm-string">'underscore'</span>
<span class="cm-variable">export</span> <span class="cm-variable">default</span> <span class="cm-variable">Math</span>
<span class="cm-variable">export</span> <span class="cm-variable">square</span> <span class="cm-punctuation">=</span> <span class="cm-punctuation">(</span><span class="cm-variable">x</span><span class="cm-punctuation">)</span> <span class="cm-operator">-></span> <span class="cm-variable">x</span> <span class="cm-operator">*</span> <span class="cm-variable">x</span>
<span class="cm-variable">export</span> <span class="cm-keyword">class</span> <span class="cm-variable">Mathematics</span>
<span class="cm-variable">least</span><span class="cm-punctuation">:</span> <span class="cm-punctuation">(</span><span class="cm-variable">x</span><span class="cm-punctuation">,</span> <span class="cm-variable">y</span><span class="cm-punctuation">)</span> <span class="cm-operator">-></span> <span class="cm-keyword">if</span> <span class="cm-variable">x</span> <span class="cm-operator">&lt;</span> <span class="cm-variable">y</span> <span class="cm-keyword">then</span> <span class="cm-variable">x</span> <span class="cm-keyword">else</span> <span class="cm-variable">y</span>
<span class="cm-variable">export</span> <span class="cm-punctuation">{</span> <span class="cm-variable">sqrt</span> <span class="cm-punctuation">}</span>
<span class="cm-variable">export</span> <span class="cm-punctuation">{</span> <span class="cm-variable">sqrt</span> <span class="cm-variable">as</span> <span class="cm-variable">squareRoot</span> <span class="cm-punctuation">}</span>
<span class="cm-variable">export</span> <span class="cm-punctuation">{</span> <span class="cm-variable">Mathematics</span> <span class="cm-variable">as</span> <span class="cm-variable">default</span><span class="cm-punctuation">,</span> <span class="cm-variable">sqrt</span> <span class="cm-variable">as</span> <span class="cm-variable">squareRoot</span> <span class="cm-punctuation">}</span>
<span class="cm-variable">export</span> <span class="cm-operator">*</span> <span class="cm-variable">from</span> <span class="cm-string">'underscore'</span>
<span class="cm-variable">export</span> <span class="cm-punctuation">{</span> <span class="cm-variable">max</span><span class="cm-punctuation">,</span> <span class="cm-variable">min</span> <span class="cm-punctuation">}</span> <span class="cm-variable">from</span> <span class="cm-string">'underscore'</span>
</pre>
</div>
<div class="col-md-6 javascript-output-column">
<textarea class="javascript-output" id="modules-js">import 'local-file.coffee';
import 'coffeescript';
import _ from 'underscore';
import * as underscore from 'underscore';
import {
now
} from 'underscore';
import {
now as currentTimestamp
} from 'underscore';
import {
first,
last
} from 'underscore';
import utilityBelt, {
each
} from 'underscore';
export default Math;
export var square = function(x) {
return x * x;
};
export var Mathematics = class Mathematics {
least(x, y) {
if (x < y) {
return x;
} else {
return y;
}
}
};
export {
sqrt
};
export {
sqrt as squareRoot
};
export {
Mathematics as default,
sqrt as squareRoot
};
export * from 'underscore';
export {
max,
min
} from 'underscore';
</textarea>
<pre class="placeholder-code"><span class="cm-keyword">import</span> <span class="cm-string">'local-file.coffee'</span>;
<span class="cm-keyword">import</span> <span class="cm-string">'coffeescript'</span>;
<span class="cm-keyword">import</span> <span class="cm-def">_</span> <span class="cm-keyword">from</span> <span class="cm-string">'underscore'</span>;
<span class="cm-keyword">import</span> <span class="cm-keyword">*</span> <span class="cm-keyword">as</span> <span class="cm-def">underscore</span> <span class="cm-keyword">from</span> <span class="cm-string">'underscore'</span>;
<span class="cm-keyword">import</span> {
<span class="cm-def">now</span>
} <span class="cm-keyword">from</span> <span class="cm-string">'underscore'</span>;
<span class="cm-keyword">import</span> {
<span class="cm-def">now</span> <span class="cm-keyword">as</span> <span class="cm-def">currentTimestamp</span>
} <span class="cm-keyword">from</span> <span class="cm-string">'underscore'</span>;
<span class="cm-keyword">import</span> {
<span class="cm-def">first</span>,
<span class="cm-def">last</span>
} <span class="cm-keyword">from</span> <span class="cm-string">'underscore'</span>;
<span class="cm-keyword">import</span> <span class="cm-def">utilityBelt</span>, {
<span class="cm-def">each</span>
} <span class="cm-keyword">from</span> <span class="cm-string">'underscore'</span>;
<span class="cm-keyword">export</span> <span class="cm-keyword">default</span> <span class="cm-variable">Math</span>;
<span class="cm-keyword">export</span> <span class="cm-keyword">var</span> <span class="cm-def">square</span> <span class="cm-operator">=</span> <span class="cm-keyword">function</span>(<span class="cm-def">x</span>) {
<span class="cm-keyword">return</span> <span class="cm-variable-2">x</span> <span class="cm-operator">*</span> <span class="cm-variable-2">x</span>;
};
<span class="cm-keyword">export</span> <span class="cm-keyword">var</span> <span class="cm-def">Mathematics</span> <span class="cm-operator">=</span> <span class="cm-keyword">class</span> <span class="cm-def">Mathematics</span> {
<span class="cm-property">least</span>(<span class="cm-def">x</span>, <span class="cm-def">y</span>) {
<span class="cm-keyword">if</span> (<span class="cm-variable-2">x</span> <span class="cm-operator">&lt;</span> <span class="cm-variable-2">y</span>) {
<span class="cm-keyword">return</span> <span class="cm-variable-2">x</span>;
} <span class="cm-keyword">else</span> {
<span class="cm-keyword">return</span> <span class="cm-variable-2">y</span>;
}
}
};
<span class="cm-keyword">export</span> {
<span class="cm-variable">sqrt</span>
};
<span class="cm-keyword">export</span> {
<span class="cm-variable">sqrt</span> <span class="cm-keyword">as</span> <span class="cm-variable">squareRoot</span>
};
<span class="cm-keyword">export</span> {
<span class="cm-variable">Mathematics</span> <span class="cm-keyword">as</span> <span class="cm-keyword">default</span>,
<span class="cm-variable">sqrt</span> <span class="cm-variable">as</span> <span class="cm-variable">squareRoot</span>
};
<span class="cm-keyword">export</span> <span class="cm-keyword">*</span> <span class="cm-keyword">from</span> <span class="cm-string">'underscore'</span>;
<span class="cm-keyword">export</span> {
<span class="cm-variable">max</span>,
<span class="cm-variable">min</span>
} <span class="cm-keyword">from</span> <span class="cm-string">'underscore'</span>;
</pre>
</div>
</div>
</aside>
<div id="modules-note" class="bookmark"></div>
<p>Note that the CoffeeScript compiler <strong>does not resolve modules</strong>; writing an <code>import</code> or <code>export</code> statement in CoffeeScript will produce an <code>import</code> or <code>export</code> statement in the resulting output. It is your responsibility to <a href="#transpilation">transpile</a> this ES2015 syntax into code that will work in your target runtimes.</p>
<p>Also note that any file with an <code>import</code> or <code>export</code> statement will be output without a <a href="#lexical-scope">top-level function safety wrapper</a>; in other words, importing or exporting modules will automatically trigger <a href="#usage">bare</a> mode for that file. This is because per the ES2015 spec, <code>import</code> or <code>export</code> statements must occur at the topmost scope.</p>
</section>
<section id="embedded">
<h2>Embedded JavaScript</h2>
<p>Hopefully, youll never need to use it, but if you ever need to intersperse snippets of JavaScript within your CoffeeScript, you can use backticks to pass it straight through.</p>
<aside class="code-example container-fluid bg-ribbed-dark" data-example="embedded">
<div class="row">
<div class="col-md-6 coffeescript-input-column">
<textarea class="coffeescript-input" id="embedded-coffee">hi = `function() {
return [document.title, "Hello JavaScript"].join(": ");
}`
</textarea>
<pre class="placeholder-code"><span class="cm-variable">hi</span> <span class="cm-punctuation">=</span> <span class="cm-punctuation">`</span><span class="cm-variable">function</span><span class="cm-punctuation">()</span> <span class="cm-punctuation">{</span>
<span class="cm-keyword">return</span> <span class="cm-punctuation">[</span><span class="cm-variable">document</span><span class="cm-punctuation">.</span><span class="cm-property">title</span><span class="cm-punctuation">,</span> <span class="cm-string">"Hello JavaScript"</span><span class="cm-punctuation">].</span><span class="cm-property">join</span><span class="cm-punctuation">(</span><span class="cm-string">": "</span><span class="cm-punctuation">);</span>
<span class="cm-punctuation">}`</span>
</pre>
</div>
<div class="col-md-6 javascript-output-column">
<textarea class="javascript-output" id="embedded-js">var hi;
hi = function() {
return [document.title, "Hello JavaScript"].join(": ");
};
</textarea>
<pre class="placeholder-code"><span class="cm-keyword">var</span> <span class="cm-def">hi</span>;
<span class="cm-variable">hi</span> <span class="cm-operator">=</span> <span class="cm-keyword">function</span>() {
<span class="cm-keyword">return</span> [<span class="cm-variable">document</span>.<span class="cm-property">title</span>, <span class="cm-string">"Hello JavaScript"</span>].<span class="cm-property">join</span>(<span class="cm-string">": "</span>);
};
</pre>
</div>
</div>
<div class="row">
<div class="col text-right">
<button type="button" class="btn btn-primary" data-action="run-code-example" data-example="embedded" data-run="hi%28%29"><small><svg class="play-button" viewBox="0 0 24 24">
<path d="M2.56-0.01v24.02L21.44 11.98 2.56-0.01z"></path>
</svg>
</small>hi()</button>
</div>
</div>
</aside>
<p>Escape backticks with backslashes: <code>\`</code> becomes <code>`</code>.</p>
<p>Escape backslashes before backticks with more backslashes: <code>\\\`</code> becomes <code>\`</code>.</p>
<aside class="code-example container-fluid bg-ribbed-dark" data-example="embedded_escaped">
<div class="row">
<div class="col-md-6 coffeescript-input-column">
<textarea class="coffeescript-input" id="embedded_escaped-coffee">markdown = `function () {
return \`In Markdown, write code like \\\`this\\\`\`;
}`
</textarea>
<pre class="placeholder-code"><span class="cm-variable">markdown</span> <span class="cm-punctuation">=</span> <span class="cm-punctuation">`</span><span class="cm-variable">function</span> <span class="cm-punctuation">()</span> <span class="cm-punctuation">{</span>
<span class="cm-keyword">return</span> <span class="cm-error">\</span><span class="cm-punctuation">`</span><span class="cm-variable">In</span> <span class="cm-variable">Markdown</span><span class="cm-punctuation">,</span> <span class="cm-variable">write</span> <span class="cm-variable">code</span> <span class="cm-variable">like</span> <span class="cm-error">\\\</span><span class="cm-punctuation">`</span><span class="cm-keyword">this</span><span class="cm-error">\\\</span><span class="cm-punctuation">`</span><span class="cm-error">\</span><span class="cm-punctuation">`;</span>
<span class="cm-punctuation">}`</span>
</pre>
</div>
<div class="col-md-6 javascript-output-column">
<textarea class="javascript-output" id="embedded_escaped-js">var markdown;
markdown = function () {
return `In Markdown, write code like \`this\``;
};
</textarea>
<pre class="placeholder-code"><span class="cm-keyword">var</span> <span class="cm-def">markdown</span>;
<span class="cm-variable">markdown</span> <span class="cm-operator">=</span> <span class="cm-keyword">function</span> () {
<span class="cm-keyword">return</span> <span class="cm-string-2">`In Markdown, write code like \`this\``</span>;
};
</pre>
</div>
</div>
<div class="row">
<div class="col text-right">
<button type="button" class="btn btn-primary" data-action="run-code-example" data-example="embedded_escaped" data-run="markdown%28%29"><small><svg class="play-button" viewBox="0 0 24 24">
<path d="M2.56-0.01v24.02L21.44 11.98 2.56-0.01z"></path>
</svg>
</small>markdown()</button>
</div>
</div>
</aside>
<p>You can also embed blocks of JavaScript using triple backticks. Thats easier than escaping backticks, if you need them inside your JavaScript block.</p>
<aside class="code-example container-fluid bg-ribbed-dark" data-example="embedded_block">
<div class="row">
<div class="col-md-6 coffeescript-input-column">
<textarea class="coffeescript-input" id="embedded_block-coffee">```
function time() {
return `The time is ${new Date().toLocaleTimeString()}`;
}
```
</textarea>
<pre class="placeholder-code"><span class="cm-punctuation">```</span>
<span class="cm-variable">function</span> <span class="cm-variable">time</span><span class="cm-punctuation">()</span> <span class="cm-punctuation">{</span>
<span class="cm-keyword">return</span> <span class="cm-punctuation">`</span><span class="cm-variable">The</span> <span class="cm-variable">time</span> <span class="cm-operator">is</span> <span class="cm-variable">$</span><span class="cm-punctuation">{</span><span class="cm-keyword">new</span> <span class="cm-variable">Date</span><span class="cm-punctuation">().</span><span class="cm-property">toLocaleTimeString</span><span class="cm-punctuation">()}`;</span>
<span class="cm-punctuation">}</span>
<span class="cm-punctuation">```</span>
</pre>
</div>
<div class="col-md-6 javascript-output-column">
<textarea class="javascript-output" id="embedded_block-js">
function time() {
return `The time is ${new Date().toLocaleTimeString()}`;
}
;
</textarea>
<pre class="placeholder-code">
<span class="cm-keyword">function</span> <span class="cm-def">time</span>() {
<span class="cm-keyword">return</span> <span class="cm-string-2">`The time is ${</span><span class="cm-keyword">new</span> <span class="cm-variable">Date</span>().<span class="cm-property">toLocaleTimeString</span>()<span class="cm-string-2">}`</span>;
}
;
</pre>
</div>
</div>
<div class="row">
<div class="col text-right">
<button type="button" class="btn btn-primary" data-action="run-code-example" data-example="embedded_block" data-run="time%28%29"><small><svg class="play-button" viewBox="0 0 24 24">
<path d="M2.56-0.01v24.02L21.44 11.98 2.56-0.01z"></path>
</svg>
</small>time()</button>
</div>
</div>
</aside>
</section>
<section id="jsx">
<h2>JSX</h2>
<p><a href="https://facebook.github.io/react/docs/introducing-jsx.html">JSX</a> is JavaScript containing interspersed XML elements. While conceived for <a href="https://facebook.github.io/react/">React</a>, it is not specific to any particular library or framework.</p>
<p>CoffeeScript supports interspersed XML elements, without the need for separate plugins or special settings. The XML elements will be compiled as such, outputting JSX that could be parsed like any normal JSX file, for example by <a href="https://babeljs.io/docs/plugins/transform-react-jsx/">Babel with the React JSX transform</a>. CoffeeScript does <em>not</em> output <code>React.createElement</code> calls or any code specific to React or any other framework. It is up to you to attach another step in your build chain to convert this JSX to whatever function calls you wish the XML elements to compile to.</p>
<p>Just like in JSX and HTML, denote XML tags using <code>&lt;</code> and <code>&gt;</code>. You can interpolate CoffeeScript code inside a tag using <code>{</code> and <code>}</code>. To avoid compiler errors, when using <code>&lt;</code> and <code>&gt;</code> to mean “less than” or “greater than,” you should wrap the operators in spaces to distinguish them from XML tags. So <code>i &lt; len</code>, not <code>i&lt;len</code>. The compiler tries to be forgiving when it can be sure what you intend, but always putting spaces around the “less than” and “greater than” operators will remove ambiguity.</p>
<aside class="code-example container-fluid bg-ribbed-dark" data-example="jsx">
<div class="row">
<div class="col-md-6 coffeescript-input-column">
<textarea class="coffeescript-input" id="jsx-coffee">renderStarRating = ({ rating, maxStars }) ->
<aside title={"Rating: #{rating} of #{maxStars} stars"}>
{for wholeStar in [0...Math.floor(rating)]
<Star className="wholeStar" key={wholeStar} />}
{if rating % 1 isnt 0
<Star className="halfStar" />}
{for emptyStar in [Math.ceil(rating)...maxStars]
<Star className="emptyStar" key={emptyStar} />}
</aside>
</textarea>
<pre class="placeholder-code"><span class="cm-variable">renderStarRating</span> <span class="cm-punctuation">=</span> <span class="cm-punctuation">({</span> <span class="cm-variable">rating</span><span class="cm-punctuation">,</span> <span class="cm-variable">maxStars</span> <span class="cm-punctuation">})</span> <span class="cm-operator">-></span>
<span class="cm-operator">&lt;</span><span class="cm-variable">aside</span> <span class="cm-variable">title</span><span class="cm-punctuation">={</span><span class="cm-string">"Rating: #{rating} of #{maxStars} stars"</span><span class="cm-punctuation">}</span><span class="cm-operator">></span>
<span class="cm-indent"> </span><span class="cm-punctuation">{</span><span class="cm-keyword">for</span> <span class="cm-variable">wholeStar</span> <span class="cm-operator">in</span> <span class="cm-punctuation">[</span><span class="cm-number">0</span><span class="cm-punctuation">...</span><span class="cm-variable">Math</span><span class="cm-punctuation">.</span><span class="cm-property">floor</span><span class="cm-punctuation">(</span><span class="cm-variable">rating</span><span class="cm-punctuation">)]</span>
<span class="cm-dedent"> </span><span class="cm-operator">&lt;</span><span class="cm-variable">Star</span> <span class="cm-variable">className</span><span class="cm-punctuation">=</span><span class="cm-string">"wholeStar"</span> <span class="cm-variable">key</span><span class="cm-punctuation">={</span><span class="cm-variable">wholeStar</span><span class="cm-punctuation">}</span> <span class="cm-operator">/></span><span class="cm-punctuation">}</span>
<span class="cm-punctuation">{</span><span class="cm-keyword">if</span> <span class="cm-variable">rating</span> <span class="cm-operator">%</span> <span class="cm-number">1</span> <span class="cm-operator">isnt</span> <span class="cm-number">0</span>
<span class="cm-dedent"> </span><span class="cm-operator">&lt;</span><span class="cm-variable">Star</span> <span class="cm-variable">className</span><span class="cm-punctuation">=</span><span class="cm-string">"halfStar"</span> <span class="cm-operator">/></span><span class="cm-punctuation">}</span>
<span class="cm-punctuation">{</span><span class="cm-keyword">for</span> <span class="cm-variable">emptyStar</span> <span class="cm-operator">in</span> <span class="cm-punctuation">[</span><span class="cm-variable">Math</span><span class="cm-punctuation">.</span><span class="cm-property">ceil</span><span class="cm-punctuation">(</span><span class="cm-variable">rating</span><span class="cm-punctuation">)...</span><span class="cm-variable">maxStars</span><span class="cm-punctuation">]</span>
<span class="cm-dedent"> </span><span class="cm-operator">&lt;</span><span class="cm-variable">Star</span> <span class="cm-variable">className</span><span class="cm-punctuation">=</span><span class="cm-string">"emptyStar"</span> <span class="cm-variable">key</span><span class="cm-punctuation">={</span><span class="cm-variable">emptyStar</span><span class="cm-punctuation">}</span> <span class="cm-operator">/></span><span class="cm-punctuation">}</span>
<span class="cm-dedent"> </span><span class="cm-operator">&lt;/</span><span class="cm-variable">aside</span><span class="cm-operator">></span>
</pre>
</div>
<div class="col-md-6 javascript-output-column">
<textarea class="javascript-output" id="jsx-js">var renderStarRating;
renderStarRating = function({rating, maxStars}) {
var emptyStar, wholeStar;
return <aside title={`Rating: ${rating} of ${maxStars} stars`}>
{(function() {
var i, ref, results;
results = [];
for (wholeStar = i = 0, ref = Math.floor(rating); (0 <= ref ? i < ref : i > ref); wholeStar = 0 <= ref ? ++i : --i) {
results.push(<Star className="wholeStar" key={wholeStar} />);
}
return results;
})()}
{(rating % 1 !== 0 ? <Star className="halfStar" /> : void 0)}
{(function() {
var i, ref, ref1, results;
results = [];
for (emptyStar = i = ref = Math.ceil(rating), ref1 = maxStars; (ref <= ref1 ? i < ref1 : i > ref1); emptyStar = ref <= ref1 ? ++i : --i) {
results.push(<Star className="emptyStar" key={emptyStar} />);
}
return results;
})()}
</aside>;
};
</textarea>
<pre class="placeholder-code"><span class="cm-keyword">var</span> <span class="cm-def">renderStarRating</span>;
<span class="cm-variable">renderStarRating</span> <span class="cm-operator">=</span> <span class="cm-keyword">function</span>({<span class="cm-def">rating</span>, <span class="cm-def">maxStars</span>}) {
<span class="cm-keyword">var</span> <span class="cm-def">emptyStar</span>, <span class="cm-def">wholeStar</span>;
<span class="cm-keyword">return</span> <span class="cm-operator">&lt;</span><span class="cm-variable">aside</span> <span class="cm-variable">title</span><span class="cm-operator">=</span>{<span class="cm-string-2">`Rating: ${</span><span class="cm-variable-2">rating</span>} <span class="cm-variable">of</span> <span class="cm-variable">$</span>{<span class="cm-variable-2">maxStars</span>} <span class="cm-variable">stars</span><span class="cm-string-2">`}></span>
<span class="cm-string-2">{(function() {</span>
<span class="cm-string-2">var i, ref, results;</span>
<span class="cm-string-2">results = [];</span>
<span class="cm-string-2">for (wholeStar = i = 0, ref = Math.floor(rating); (0 &lt;= ref ? i &lt; ref : i > ref); wholeStar = 0 &lt;= ref ? ++i : --i) {</span>
<span class="cm-string-2">results.push(&lt;Star className="wholeStar" key={wholeStar} />);</span>
<span class="cm-string-2">}</span>
<span class="cm-string-2">return results;</span>
<span class="cm-string-2">})()}</span>
<span class="cm-string-2">{(rating % 1 !== 0 ? &lt;Star className="halfStar" /> : void 0)}</span>
<span class="cm-string-2">{(function() {</span>
<span class="cm-string-2">var i, ref, ref1, results;</span>
<span class="cm-string-2">results = [];</span>
<span class="cm-string-2">for (emptyStar = i = ref = Math.ceil(rating), ref1 = maxStars; (ref &lt;= ref1 ? i &lt; ref1 : i > ref1); emptyStar = ref &lt;= ref1 ? ++i : --i) {</span>
<span class="cm-string-2">results.push(&lt;Star className="emptyStar" key={emptyStar} />);</span>
<span class="cm-string-2">}</span>
<span class="cm-string-2">return results;</span>
<span class="cm-string-2">})()}</span>
<span class="cm-string-2">&lt;/aside>;</span>
<span class="cm-string-2">};</span>
</pre>
</div>
</div>
</aside>
<p>Older plugins or forks of CoffeeScript supported JSX syntax and referred to it as CSX or CJSX. They also often used a <code>.cjsx</code> file extension, but this is no longer necessary; regular <code>.coffee</code> will do.</p>
</section>
</section>
<section id="type-annotations">
<h2>Type Annotations</h2>
<p>Static type checking can be achieved in CoffeeScript by using <a href="https://flow.org/">Flow</a>s <a href="https://flow.org/en/docs/types/comments/">Comment Types syntax</a>:</p>
<aside class="code-example container-fluid bg-ribbed-dark" data-example="type_annotations">
<div class="row">
<div class="col-md-6 coffeescript-input-column">
<textarea class="coffeescript-input" id="type_annotations-coffee"># @flow
###::
type Obj = {
num: number,
};
###
fn = (str ###: string ###, obj ###: Obj ###) ###: string ### ->
str + obj.num
</textarea>
<pre class="placeholder-code"><span class="cm-comment"># @flow</span>
<span class="cm-comment">###::</span>
<span class="cm-comment">type Obj = {</span>
<span class="cm-comment"> num: number,</span>
<span class="cm-comment">};</span>
<span class="cm-comment">###</span>
<span class="cm-variable">fn</span> <span class="cm-punctuation">=</span> <span class="cm-punctuation">(</span><span class="cm-variable">str</span> <span class="cm-comment">###: string ###</span><span class="cm-punctuation">,</span> <span class="cm-variable">obj</span> <span class="cm-comment">###: Obj ###</span><span class="cm-punctuation">)</span> <span class="cm-comment">###: string ###</span> <span class="cm-operator">-></span>
<span class="cm-variable">str</span> <span class="cm-operator">+</span> <span class="cm-variable">obj</span><span class="cm-punctuation">.</span><span class="cm-property">num</span>
</pre>
</div>
<div class="col-md-6 javascript-output-column">
<textarea class="javascript-output" id="type_annotations-js">// @flow
/*::
type Obj = {
num: number,
};
*/
var fn;
fn = function(str/*: string */, obj/*: Obj */)/*: string */ {
return str + obj.num;
};
</textarea>
<pre class="placeholder-code"><span class="cm-comment">// @flow</span>
<span class="cm-comment">/*::</span>
<span class="cm-comment">type Obj = {</span>
<span class="cm-comment"> num: number,</span>
<span class="cm-comment">};</span>
<span class="cm-comment">*/</span>
<span class="cm-keyword">var</span> <span class="cm-def">fn</span>;
<span class="cm-variable">fn</span> <span class="cm-operator">=</span> <span class="cm-keyword">function</span>(<span class="cm-def">str</span><span class="cm-comment">/*: string */</span>, <span class="cm-def">obj</span><span class="cm-comment">/*: Obj */</span>)<span class="cm-comment">/*: string */</span> {
<span class="cm-keyword">return</span> <span class="cm-variable-2">str</span> <span class="cm-operator">+</span> <span class="cm-variable-2">obj</span>.<span class="cm-property">num</span>;
};
</pre>
</div>
</div>
</aside>
<p>CoffeeScript does not do any type checking itself; the JavaScript output you see above needs to get passed to Flow for it to validate your code. We expect most people will use a <a href="#es2015plus-output">build tool</a> for this, but heres how to do it the simplest way possible using the <a href="#cli">CoffeeScript</a> and <a href="https://flow.org/en/docs/usage/">Flow</a> command-line tools, assuming youve already <a href="https://flow.org/en/docs/install/">installed Flow</a> and the <a href="#installation">latest CoffeeScript</a> in your project folder:</p>
<blockquote class="uneditable-code-block"><pre><code class="language-bash">coffee --bare --no-header --compile app.coffee &amp;&amp; npm run flow
</code></pre>
</blockquote><p><code>--bare</code> and <code>--no-header</code> are important because Flow requires the first line of the file to be the comment <code>// @flow</code>. If you configure your build chain to compile CoffeeScript and pass the result to Flow in-memory, you can get better performance than this example; and a proper build tool should be able to watch your CoffeeScript files and recompile and type-check them for you on save.</p>
<p>If you know of another way to achieve static type checking with CoffeeScript, please <a href="https://github.com/jashkenas/coffeescript/issues/new">create an issue</a> and let us know.</p>
</section>
<section id="literate">
<h2>Literate CoffeeScript</h2>
<p>Besides being used as an ordinary programming language, CoffeeScript may also be written in “literate” mode. If you name your file with a <code>.litcoffee</code> extension, you can write it as a Markdown document — a document that also happens to be executable CoffeeScript code. The compiler will treat any indented blocks (Markdowns way of indicating source code) as executable code, and ignore the rest as comments. Code blocks must also be separated from comments by at least one blank line.</p>
<p>Just for kicks, a little bit of the compiler is currently implemented in this fashion: See it <a href="https://gist.github.com/jashkenas/3fc3c1a8b1009c00d9df">as a document</a>, <a href="https://raw.githubusercontent.com/jashkenas/coffeescript/master/src/scope.litcoffee">raw</a>, and <a href="http://cl.ly/LxEu">properly highlighted in a text editor</a>.</p>
<p>A few caveats:</p>
<ul>
<li>Code blocks need to maintain consistent indentation relative to each other. When the compiler parses your Literate CoffeeScript file, it first discards all the non-code block lines and then parses the remainder as a regular CoffeeScript file. Therefore the code blocks need to be written as if the comment lines dont exist, with consistent indentation (including whether they are indented with tabs or spaces).</li>
<li>Along those lines, code blocks within list items or blockquotes are not treated as executable code. Since list items and blockquotes imply their own indentation, it would be ambiguous how to treat indentation between successive code blocks when some are within these other blocks and some are not.</li>
<li>List items can be at most only one paragraph long. The second paragraph of a list item would be indented after a blank line, and therefore indistinguishable from a code block.</li>
</ul>
</section>
<section id="source-maps">
<h2>Source Maps</h2>
<p>CoffeeScript includes support for generating source maps, a way to tell your JavaScript engine what part of your CoffeeScript program matches up with the code being evaluated. Browsers that support it can automatically use source maps to show your original source code in the debugger. To generate source maps alongside your JavaScript files, pass the <code>--map</code> or <code>-m</code> flag to the compiler.</p>
<p>For a full introduction to source maps, how they work, and how to hook them up in your browser, read the <a href="https://www.html5rocks.com/en/tutorials/developertools/sourcemaps/">HTML5 Tutorial</a>.</p>
</section>
<section id="cake">
<h2>Cake, and Cakefiles</h2>
<p>CoffeeScript includes a (very) simple build system similar to <a href="http://www.gnu.org/software/make/">Make</a> and <a href="http://rake.rubyforge.org/">Rake</a>. Naturally, its called Cake, and is used for the tasks that build and test the CoffeeScript language itself. Tasks are defined in a file named <code>Cakefile</code>, and can be invoked by running <code>cake [task]</code> from within the directory. To print a list of all the tasks and options, just type <code>cake</code>.</p>
<p>Task definitions are written in CoffeeScript, so you can put arbitrary code in your Cakefile. Define a task with a name, a long description, and the function to invoke when the task is run. If your task takes a command-line option, you can define the option with short and long flags, and it will be made available in the <code>options</code> object. Heres a task that uses the Node.js API to rebuild CoffeeScripts parser:</p>
<aside class="code-example container-fluid bg-ribbed-dark" data-example="cake_tasks">
<div class="row">
<div class="col-md-6 coffeescript-input-column">
<textarea class="coffeescript-input" id="cake_tasks-coffee">fs = require 'fs'
option '-o', '--output [DIR]', 'directory for compiled code'
task 'build:parser', 'rebuild the Jison parser', (options) ->
require 'jison'
code = require('./lib/grammar').parser.generate()
dir = options.output or 'lib'
fs.writeFile "#{dir}/parser.js", code
</textarea>
<pre class="placeholder-code"><span class="cm-variable">fs</span> <span class="cm-punctuation">=</span> <span class="cm-variable">require</span> <span class="cm-string">'fs'</span>
<span class="cm-variable">option</span> <span class="cm-string">'-o'</span><span class="cm-punctuation">,</span> <span class="cm-string">'--output [DIR]'</span><span class="cm-punctuation">,</span> <span class="cm-string">'directory for compiled code'</span>
<span class="cm-variable">task</span> <span class="cm-string">'build:parser'</span><span class="cm-punctuation">,</span> <span class="cm-string">'rebuild the Jison parser'</span><span class="cm-punctuation">,</span> <span class="cm-punctuation">(</span><span class="cm-variable">options</span><span class="cm-punctuation">)</span> <span class="cm-operator">-></span>
<span class="cm-variable">require</span> <span class="cm-string">'jison'</span>
<span class="cm-variable">code</span> <span class="cm-punctuation">=</span> <span class="cm-variable">require</span><span class="cm-punctuation">(</span><span class="cm-string">'./lib/grammar'</span><span class="cm-punctuation">).</span><span class="cm-property">parser</span><span class="cm-punctuation">.</span><span class="cm-property">generate</span><span class="cm-punctuation">()</span>
<span class="cm-variable">dir</span> <span class="cm-punctuation">=</span> <span class="cm-variable">options</span><span class="cm-punctuation">.</span><span class="cm-property">output</span> <span class="cm-operator">or</span> <span class="cm-string">'lib'</span>
<span class="cm-variable">fs</span><span class="cm-punctuation">.</span><span class="cm-property">writeFile</span> <span class="cm-string">"#{dir}/parser.js"</span><span class="cm-punctuation">,</span> <span class="cm-variable">code</span>
</pre>
</div>
<div class="col-md-6 javascript-output-column">
<textarea class="javascript-output" id="cake_tasks-js">var fs;
fs = require('fs');
option('-o', '--output [DIR]', 'directory for compiled code');
task('build:parser', 'rebuild the Jison parser', function(options) {
var code, dir;
require('jison');
code = require('./lib/grammar').parser.generate();
dir = options.output || 'lib';
return fs.writeFile(`${dir}/parser.js`, code);
});
</textarea>
<pre class="placeholder-code"><span class="cm-keyword">var</span> <span class="cm-def">fs</span>;
<span class="cm-variable">fs</span> <span class="cm-operator">=</span> <span class="cm-variable">require</span>(<span class="cm-string">'fs'</span>);
<span class="cm-variable">option</span>(<span class="cm-string">'-o'</span>, <span class="cm-string">'--output [DIR]'</span>, <span class="cm-string">'directory for compiled code'</span>);
<span class="cm-variable">task</span>(<span class="cm-string">'build:parser'</span>, <span class="cm-string">'rebuild the Jison parser'</span>, <span class="cm-keyword">function</span>(<span class="cm-def">options</span>) {
<span class="cm-keyword">var</span> <span class="cm-def">code</span>, <span class="cm-def">dir</span>;
<span class="cm-variable">require</span>(<span class="cm-string">'jison'</span>);
<span class="cm-variable-2">code</span> <span class="cm-operator">=</span> <span class="cm-variable">require</span>(<span class="cm-string">'./lib/grammar'</span>).<span class="cm-property">parser</span>.<span class="cm-property">generate</span>();
<span class="cm-variable-2">dir</span> <span class="cm-operator">=</span> <span class="cm-variable-2">options</span>.<span class="cm-property">output</span> <span class="cm-operator">||</span> <span class="cm-string">'lib'</span>;
<span class="cm-keyword">return</span> <span class="cm-variable">fs</span>.<span class="cm-property">writeFile</span>(<span class="cm-string-2">`${</span><span class="cm-variable-2">dir</span><span class="cm-string-2">}/parser.js`</span>, <span class="cm-variable-2">code</span>);
});
</pre>
</div>
</div>
</aside>
<p>If you need to invoke one task before another — for example, running <code>build</code> before <code>test</code>, you can use the <code>invoke</code> function: <code>invoke 'build'</code>. Cake tasks are a minimal way to expose your CoffeeScript functions to the command line, so <a href="/v2/annotated-source/cake.html">dont expect any fanciness built-in</a>. If you need dependencies, or async callbacks, its best to put them in your code itself — not the cake task.</p>
</section>
<section id="scripts">
<h2><code>&quot;text/coffeescript&quot;</code> Script Tags</h2>
<p>While its not recommended for serious use, CoffeeScripts may be included directly within the browser using <code>&lt;script type=&quot;text/coffeescript&quot;&gt;</code> tags. The source includes a compressed and minified version of the compiler (<a href="/v2/browser-compiler/coffeescript.js">Download current version here, 51k when gzipped</a>) as <code>docs/v2/browser-compiler/coffeescript.js</code>. Include this file on a page with inline CoffeeScript tags, and it will compile and evaluate them in order.</p>
<p>The usual caveats about CoffeeScript apply — your inline scripts will run within a closure wrapper, so if you want to expose global variables or functions, attach them to the <code>window</code> object.</p>
</section>
<section id="resources">
<h2>Resources</h2>
<ul>
<li><a href="https://github.com/jashkenas/coffeescript/">CoffeeScript on GitHub</a></li>
<li><a href="https://github.com/jashkenas/coffeescript/issues">CoffeeScript Issues</a><br>
Bug reports, feature proposals, and ideas for changes to the language belong here.</li>
<li><a href="https://groups.google.com/forum/#!forum/coffeescript">CoffeeScript Google Group</a><br>
If youd like to ask a question, the mailing list is a good place to get help.</li>
<li><a href="https://github.com/jashkenas/coffeescript/wiki">The CoffeeScript Wiki</a><br>
If youve ever learned a neat CoffeeScript tip or trick, or ran into a gotcha — share it on the wiki. The wiki also serves as a directory of handy <a href="https://github.com/jashkenas/coffeescript/wiki/Text-editor-plugins">text editor extensions</a>, <a href="https://github.com/jashkenas/coffeescript/wiki/Web-framework-plugins">web framework plugins</a>, and general <a href="https://github.com/jashkenas/coffeescript/wiki/Build-tools">CoffeeScript build tools</a>.</li>
<li><a href="https://github.com/jashkenas/coffeescript/wiki/FAQ">The FAQ</a><br>
Perhaps your CoffeeScript-related question has been asked before. Check the FAQ first.</li>
<li><a href="http://js2.coffee/">JS2Coffee</a><br>
Is a very well done reverse JavaScript-to-CoffeeScript compiler. Its not going to be perfect (infer what your JavaScript classes are, when you need bound functions, and so on…) — but its a great starting point for converting simple scripts.</li>
<li><a href="https://github.com/jashkenas/coffeescript/tree/master/documentation/site">High-Rez Logo</a><br>
The CoffeeScript logo is available in SVG for use in presentations.</li>
</ul>
<section id="books">
<h2>Books</h2>
<p>There are a number of excellent resources to help you get started with CoffeeScript, some of which are freely available online.</p>
<ul>
<li><a href="http://arcturo.github.io/library/coffeescript/">The Little Book on CoffeeScript</a> is a brief 5-chapter introduction to CoffeeScript, written with great clarity and precision by <a href="http://alexmaccaw.co.uk/">Alex MacCaw</a>.</li>
<li><a href="http://autotelicum.github.io/Smooth-CoffeeScript/">Smooth CoffeeScript</a> is a reimagination of the excellent book <a href="http://eloquentjavascript.net/">Eloquent JavaScript</a>, as if it had been written in CoffeeScript instead. Covers language features as well as the functional and object oriented programming styles. By <a href="https://github.com/autotelicum">E. Hoigaard</a>.</li>
<li><a href="http://pragprog.com/book/tbcoffee/coffeescript">CoffeeScript: Accelerated JavaScript Development</a> is <a href="http://trevorburnham.com/">Trevor Burnham</a>s thorough introduction to the language. By the end of the book, youll have built a fast-paced multiplayer word game, writing both the client-side and Node.js portions in CoffeeScript.</li>
<li><a href="https://www.packtpub.com/web-development/coffeescript-programming-jquery-rails-and-nodejs">CoffeeScript Programming with jQuery, Rails, and Node.js</a> is a new book by Michael Erasmus that covers CoffeeScript with an eye towards real-world usage both in the browser (jQuery) and on the server-side (Rails, Node).</li>
<li><a href="https://leanpub.com/coffeescript-ristretto/read">CoffeeScript Ristretto</a> is a deep dive into CoffeeScripts semantics from simple functions up through closures, higher-order functions, objects, classes, combinators, and decorators. By <a href="http://braythwayt.com/">Reg Braithwaite</a>.</li>
<li><a href="https://efendibooks.com/minibooks/testing-with-coffeescript">Testing with CoffeeScript</a> is a succinct and freely downloadable guide to building testable applications with CoffeeScript and Jasmine.</li>
<li><a href="https://www.packtpub.com/web-development/coffeescript-application-development">CoffeeScript Application Development</a> from Packt, introduces CoffeeScript while walking through the process of building a demonstration web application. A <a href="https://www.packtpub.com/web-development/coffeescript-application-development-cookbook">CoffeeScript Application Development Coookbook</a> with over 90 “recipes” is also available.</li>
<li><a href="https://www.manning.com/books/coffeescript-in-action">CoffeeScript in Action</a> from Manning Publications, covers CoffeeScript syntax, composition techniques and application development.</li>
<li><a href="https://www.dpunkt.de/buecher/4021/coffeescript.html">CoffeeScript: Die Alternative zu JavaScript</a> from dpunkt.verlag, is the first CoffeeScript book in Deutsch.</li>
</ul>
</section>
<section id="screencasts">
<h2>Screencasts</h2>
<ul>
<li><a href="http://coffeescript.codeschool.com/">A Sip of CoffeeScript</a> is a <a href="https://www.codeschool.com">Code School Course</a> which combines 6 screencasts with in-browser coding to make learning fun. The first level is free to try out.</li>
<li><a href="https://www.pluralsight.com/courses/meet-coffeescript">Meet CoffeeScript</a> is a 75-minute long screencast by PeepCode, now <a href="https://www.pluralsight.com/">PluralSight</a>. Highly memorable for its animations which demonstrate transforming CoffeeScript into the equivalent JS.</li>
<li>If youre looking for less of a time commitment, RailsCasts <a href="http://railscasts.com/episodes/267-coffeescript-basics">CoffeeScript Basics</a> should have you covered, hitting all of the important notes about CoffeeScript in 11 minutes.</li>
</ul>
</section>
<section id="examples">
<h2>Examples</h2>
<p>The <a href="https://github.com/trending?l=coffeescript&amp;since=monthly">best list of open-source CoffeeScript examples</a> can be found on GitHub. But just to throw out a few more:</p>
<ul>
<li><strong>GitHub</strong>s <a href="https://hubot.github.com/">Hubot</a>, a friendly IRC robot that can perform any number of useful and useless tasks.</li>
<li><strong>sstephenson</strong>s <a href="http://pow.cx/">Pow</a>, a zero-configuration Rack server, with comprehensive annotated source.</li>
<li><strong>technoweenie</strong>s <a href="https://github.com/technoweenie/coffee-resque">Coffee-Resque</a>, a port of <a href="https://github.com/defunkt/resque">Resque</a> for Node.js.</li>
<li><strong>stephank</strong>s <a href="https://github.com/stephank/orona">Orona</a>, a remake of the Bolo tank game for modern browsers.</li>
<li><strong>GitHub</strong>s <a href="https://atom.io/">Atom</a>, a hackable text editor built on web technologies.</li>
<li><strong>Basecamp</strong>s <a href="https://trix-editor.org/">Trix</a>, a rich text editor for web apps.</li>
</ul>
</section>
<section id="chat">
<h2>Web Chat (IRC)</h2>
<p>Quick help and advice can often be found in the CoffeeScript IRC room <code>#coffeescript</code> on <code>irc.freenode.net</code>, which you can <a href="http://webchat.freenode.net/?channels=coffeescript">join via your web browser</a>.</p>
</section>
<section id="annotated-source">
<h2>Annotated Source</h2>
<p>You can browse the CoffeeScript 2.3.1 source in readable, annotated form <a href="annotated-source/">here</a>. You can also jump directly to a particular source file:</p>
<ul>
<li><a href="annotated-source/grammar.html">Grammar Rules — src/grammar</a></li>
<li><a href="annotated-source/lexer.html">Lexing Tokens — src/lexer</a></li>
<li><a href="annotated-source/rewriter.html">The Rewriter — src/rewriter</a></li>
<li><a href="annotated-source/nodes.html">The Syntax Tree — src/nodes</a></li>
<li><a href="annotated-source/scope.html">Lexical Scope — src/scope</a></li>
<li><a href="annotated-source/helpers.html">Helpers &amp; Utility Functions — src/helpers</a></li>
<li><a href="annotated-source/coffeescript.html">The CoffeeScript Module — src/coffeescript</a></li>
<li><a href="annotated-source/cake.html">Cake &amp; Cakefiles — src/cake</a></li>
<li><a href="annotated-source/command.html">“coffee” Command-Line Utility — src/command</a></li>
<li><a href="annotated-source/optparse.html">Option Parsing — src/optparse</a></li>
<li><a href="annotated-source/repl.html">Interactive REPL — src/repl</a></li>
<li><a href="annotated-source/sourcemap.html">Source Maps — src/sourcemap</a></li>
</ul>
</section>
<section id="contributing">
<h2>Contributing</h2>
<p>Contributions are welcome! Feel free to fork <a href="https://github.com/jashkenas/coffeescript">the repo</a> and submit a pull request.</p>
<p><a href="#unsupported">Some features of ECMAScript are intentionally unsupported</a>. Please review both the open and closed <a href="https://github.com/jashkenas/coffeescript/issues">issues on GitHub</a> to see if the feature youre looking for has already been discussed. As a general rule, we dont support ECMAScript syntax for features that arent yet finalized (at Stage 4 in the proposal approval process).</p>
<p>For more resources on adding to CoffeeScript, please see <a href="https://github.com/jashkenas/coffeescript/wiki/%5BHowto%5D-Hacking-on-the-CoffeeScript-Compiler">the Wiki</a>, especially <a href="https://github.com/jashkenas/coffeescript/wiki/%5BHowTo%5D-How-parsing-works">How The Parser Works</a>.</p>
<p>There are several things you can do to increase your odds of having your pull request accepted:</p>
<ul>
<li>Create tests! Any pull request should probably include basic tests to verify you didnt break anything, or future changes wont break your code.</li>
<li>Follow the style of the rest of the CoffeeScript codebase.</li>
<li>Ensure any ECMAScript syntax is mature (at Stage 4), with no further potential changes.</li>
<li>Add only features that have broad utility, rather than a feature aimed at a specific use case or framework.</li>
</ul>
<p>Of course, its entirely possible that you have a great addition, but it doesnt fit within these constraints. Feel free to roll your own solution; you will have <a href="https://github.com/jashkenas/coffeescript/wiki/In-The-Wild">plenty of company</a>.</p>
</section>
</section>
<section id="unsupported">
<h2>Unsupported ECMAScript Features</h2>
<p>There are a few ECMAScript features that CoffeeScript intentionally doesnt support.</p>
<section id="unsupported-let-const">
<h3><code>let</code> and <code>const</code>: block-scoped and reassignment-protected variables</h3>
<p>When CoffeeScript was designed, <code>var</code> was <a href="https://github.com/jashkenas/coffeescript/issues/238#issuecomment-153502">intentionally omitted</a>. This was to spare developers the mental housekeeping of needing to worry about variable <em>declaration</em> (<code>var foo</code>) as opposed to variable <em>assignment</em> (<code>foo = 1</code>). The CoffeeScript compiler automatically takes care of declaration for you, by generating <code>var</code> statements at the top of every function scope. This makes it impossible to accidentally declare a global variable.</p>
<p><code>let</code> and <code>const</code> add a useful ability to JavaScript in that you can use them to declare variables within a <em>block</em> scope, for example within an <code>if</code> statement body or a <code>for</code> loop body, whereas <code>var</code> always declares variables in the scope of an entire function. When CoffeeScript 2 was designed, there was much discussion of whether this functionality was useful enough to outweigh the simplicity offered by never needing to consider variable declaration in CoffeeScript. In the end, it was decided that the simplicity was more valued. In CoffeeScript there remains only one type of variable.</p>
<p>Keep in mind that <code>const</code> only protects you from <em>reassigning</em> a variable; it doesnt prevent the variables value from changing, the way constants usually do in other languages:</p>
<blockquote class="uneditable-code-block"><pre><code class="language-js"><span class="keyword">const</span> obj = {<span class="attr">foo</span>: <span class="string">'bar'</span>};
obj.foo = <span class="string">'baz'</span>; <span class="comment">// Allowed!</span>
obj = {}; <span class="comment">// Throws error</span>
</code></pre>
</blockquote>
</section>
<section id="unsupported-named-functions">
<h3>Named functions and function declarations</h3>
<p>Newcomers to CoffeeScript often wonder how to generate the JavaScript <code>function foo() {}</code>, as opposed to the <code>foo = function() {}</code> that CoffeeScript produces. The first form is a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function">function declaration</a>, and the second is a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/function">function expression</a>. As stated above, in CoffeeScript <a href="#expressions">everything is an expression</a>, so naturally we favor the expression form. Supporting only one variant helps avoid confusing bugs that can arise from the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function#Function_declaration_hoisting">subtle differences between the two forms</a>.</p>
<p>Technically, <code>foo = function() {}</code> is creating an anonymous function that gets assigned to a variable named <code>foo</code>. Some very early versions of CoffeeScript named this function, e.g. <code>foo = function foo() {}</code>, but this was dropped because of compatibility issues with Internet Explorer. For a while this annoyed people, as these functions would be unnamed in stack traces; but modern JavaScript runtimes <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name">infer the names of such anonymous functions</a> from the names of the variables to which theyre assigned. Given that this is the case, its simplest to just preserve the current behavior.</p>
</section>
<section id="unsupported-get-set">
<h3><code>get</code> and <code>set</code> keyword shorthand syntax</h3>
<p><code>get</code> and <code>set</code>, as keywords preceding functions or class methods, are intentionally unimplemented in CoffeeScript.</p>
<p>This is to avoid grammatical ambiguity, since in CoffeeScript such a construct looks identical to a function call (e.g. <code>get(function foo() {})</code>); and because there is an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty">alternate syntax</a> that is slightly more verbose but just as effective:</p>
<aside class="code-example container-fluid bg-ribbed-dark" data-example="get_set">
<div class="row">
<div class="col-md-6 coffeescript-input-column">
<textarea class="coffeescript-input" id="get_set-coffee">screen =
width: 1200
ratio: 16/9
Object.defineProperty screen, 'height',
get: ->
this.width / this.ratio
set: (val) ->
this.width = val * this.ratio
</textarea>
<pre class="placeholder-code"><span class="cm-variable">screen</span> <span class="cm-punctuation">=</span>
<span class="cm-indent"> </span><span class="cm-variable">width</span><span class="cm-punctuation">:</span> <span class="cm-number">1200</span>
<span class="cm-variable">ratio</span><span class="cm-punctuation">:</span> <span class="cm-number">16</span><span class="cm-operator">/</span><span class="cm-number">9</span>
<span class="cm-variable">Object</span><span class="cm-punctuation">.</span><span class="cm-property">defineProperty</span> <span class="cm-variable">screen</span><span class="cm-punctuation">,</span> <span class="cm-string">'height'</span><span class="cm-punctuation">,</span>
<span class="cm-indent"> </span><span class="cm-variable">get</span><span class="cm-punctuation">:</span> <span class="cm-operator">-></span>
<span class="cm-keyword">this</span><span class="cm-punctuation">.</span><span class="cm-property">width</span> <span class="cm-operator">/</span> <span class="cm-keyword">this</span><span class="cm-punctuation">.</span><span class="cm-property">ratio</span>
<span class="cm-dedent"> </span><span class="cm-variable">set</span><span class="cm-punctuation">:</span> <span class="cm-punctuation">(</span><span class="cm-variable">val</span><span class="cm-punctuation">)</span> <span class="cm-operator">-></span>
<span class="cm-keyword">this</span><span class="cm-punctuation">.</span><span class="cm-property">width</span> <span class="cm-punctuation">=</span> <span class="cm-variable">val</span> <span class="cm-operator">*</span> <span class="cm-keyword">this</span><span class="cm-punctuation">.</span><span class="cm-property">ratio</span>
</pre>
</div>
<div class="col-md-6 javascript-output-column">
<textarea class="javascript-output" id="get_set-js">var screen;
screen = {
width: 1200,
ratio: 16 / 9
};
Object.defineProperty(screen, 'height', {
get: function() {
return this.width / this.ratio;
},
set: function(val) {
return this.width = val * this.ratio;
}
});
</textarea>
<pre class="placeholder-code"><span class="cm-keyword">var</span> <span class="cm-def">screen</span>;
<span class="cm-variable">screen</span> <span class="cm-operator">=</span> {
<span class="cm-property">width</span>: <span class="cm-number">1200</span>,
<span class="cm-property">ratio</span>: <span class="cm-number">16</span> <span class="cm-operator">/</span> <span class="cm-number">9</span>
};
<span class="cm-variable">Object</span>.<span class="cm-property">defineProperty</span>(<span class="cm-variable">screen</span>, <span class="cm-string">'height'</span>, {
<span class="cm-property">get</span>: <span class="cm-keyword">function</span>() {
<span class="cm-keyword">return</span> <span class="cm-keyword">this</span>.<span class="cm-property">width</span> <span class="cm-operator">/</span> <span class="cm-keyword">this</span>.<span class="cm-property">ratio</span>;
},
<span class="cm-property">set</span>: <span class="cm-keyword">function</span>(<span class="cm-def">val</span>) {
<span class="cm-keyword">return</span> <span class="cm-keyword">this</span>.<span class="cm-property">width</span> <span class="cm-operator">=</span> <span class="cm-variable-2">val</span> <span class="cm-operator">*</span> <span class="cm-keyword">this</span>.<span class="cm-property">ratio</span>;
}
});
</pre>
</div>
</div>
<div class="row">
<div class="col text-right">
<button type="button" class="btn btn-primary" data-action="run-code-example" data-example="get_set" data-run="screen.height"><small><svg class="play-button" viewBox="0 0 24 24">
<path d="M2.56-0.01v24.02L21.44 11.98 2.56-0.01z"></path>
</svg>
</small>screen.height</button>
</div>
</div>
</aside>
</section>
</section>
<section id="breaking-changes">
<h2>Breaking Changes From CoffeeScript 1.x to 2</h2>
<p>CoffeeScript 2 aims to output as much idiomatic ES2015+ syntax as possible with as few breaking changes from CoffeeScript 1.x as possible. Some breaking changes, unfortunately, were unavoidable.</p>
<section id="breaking-changes-fat-arrow">
<h3>Bound (fat arrow) functions</h3>
<p>In CoffeeScript 1.x, <code>=&gt;</code> compiled to a regular <code>function</code> but with references to <code>this</code>/<code>@</code> rewritten to use the outer scopes <code>this</code>, or with the inner function bound to the outer scope via <code>.bind</code> (hence the name “bound function”). In CoffeeScript 2, <code>=&gt;</code> compiles to <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions">ES2015s <code>=&gt;</code></a>, which behaves slightly differently. The largest difference is that in ES2015, <code>=&gt;</code> functions lack an <code>arguments</code> object:</p>
<aside class="code-example container-fluid bg-ribbed-dark" data-example="breaking_change_fat_arrow">
<div class="row">
<div class="col-md-6 coffeescript-input-column">
<textarea class="coffeescript-input" id="breaking_change_fat_arrow-coffee">outer = ->
inner = => Array.from arguments
inner()
outer(1, 2) # Returns '' in CoffeeScript 1.x, '1, 2' in CoffeeScript 2
</textarea>
<pre class="placeholder-code"><span class="cm-variable">outer</span> <span class="cm-punctuation">=</span> <span class="cm-operator">-></span>
<span class="cm-variable">inner</span> <span class="cm-punctuation">=</span> <span class="cm-operator">=></span> <span class="cm-variable">Array</span><span class="cm-punctuation">.</span><span class="cm-property">from</span> <span class="cm-variable">arguments</span>
<span class="cm-variable">inner</span><span class="cm-punctuation">()</span>
<span class="cm-variable">outer</span><span class="cm-punctuation">(</span><span class="cm-number">1</span><span class="cm-punctuation">,</span> <span class="cm-number">2</span><span class="cm-punctuation">)</span> <span class="cm-comment"># Returns '' in CoffeeScript 1.x, '1, 2' in CoffeeScript 2</span>
</pre>
</div>
<div class="col-md-6 javascript-output-column">
<textarea class="javascript-output" id="breaking_change_fat_arrow-js">var outer;
outer = function() {
var inner;
inner = () => {
return Array.from(arguments);
};
return inner();
};
outer(1, 2); // Returns '' in CoffeeScript 1.x, '1, 2' in CoffeeScript 2
</textarea>
<pre class="placeholder-code"><span class="cm-keyword">var</span> <span class="cm-def">outer</span>;
<span class="cm-variable">outer</span> <span class="cm-operator">=</span> <span class="cm-keyword">function</span>() {
<span class="cm-keyword">var</span> <span class="cm-def">inner</span>;
<span class="cm-variable-2">inner</span> <span class="cm-operator">=</span> () <span class="cm-operator">=></span> {
<span class="cm-keyword">return</span> <span class="cm-variable">Array</span>.<span class="cm-property">from</span>(<span class="cm-variable-2">arguments</span>);
};
<span class="cm-keyword">return</span> <span class="cm-variable-2">inner</span>();
};
<span class="cm-variable">outer</span>(<span class="cm-number">1</span>, <span class="cm-number">2</span>); <span class="cm-comment">// Returns '' in CoffeeScript 1.x, '1, 2' in CoffeeScript 2</span>
</pre>
</div>
</div>
<div class="row">
<div class="col text-right">
<button type="button" class="btn btn-primary" data-action="run-code-example" data-example="breaking_change_fat_arrow" data-run="outer%281%2C%202%29"><small><svg class="play-button" viewBox="0 0 24 24">
<path d="M2.56-0.01v24.02L21.44 11.98 2.56-0.01z"></path>
</svg>
</small>outer(1, 2)</button>
</div>
</div>
</aside>
</section>
<section id="breaking-changes-default-values">
<h3>Default values for function parameters and destructured elements</h3>
<p>Per the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters">ES2015 spec regarding function default parameters</a> and <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Default_values">destructuring default values</a>, default values are only applied when a value is missing or <code>undefined</code>. In CoffeeScript 1.x, the default value would be applied in those cases but also if the value was <code>null</code>.</p>
<aside class="code-example container-fluid bg-ribbed-dark" data-example="breaking_change_function_parameter_default_values">
<div class="row">
<div class="col-md-6 coffeescript-input-column">
<textarea class="coffeescript-input" id="breaking_change_function_parameter_default_values-coffee">f = (a = 1) -> a
f(null) # Returns 1 in CoffeeScript 1.x, null in CoffeeScript 2
</textarea>
<pre class="placeholder-code"><span class="cm-variable">f</span> <span class="cm-punctuation">=</span> <span class="cm-punctuation">(</span><span class="cm-variable">a</span> <span class="cm-punctuation">=</span> <span class="cm-number">1</span><span class="cm-punctuation">)</span> <span class="cm-operator">-></span> <span class="cm-variable">a</span>
<span class="cm-variable">f</span><span class="cm-punctuation">(</span><span class="cm-atom">null</span><span class="cm-punctuation">)</span> <span class="cm-comment"># Returns 1 in CoffeeScript 1.x, null in CoffeeScript 2</span>
</pre>
</div>
<div class="col-md-6 javascript-output-column">
<textarea class="javascript-output" id="breaking_change_function_parameter_default_values-js">var f;
f = function(a = 1) {
return a;
};
f(null); // Returns 1 in CoffeeScript 1.x, null in CoffeeScript 2
</textarea>
<pre class="placeholder-code"><span class="cm-keyword">var</span> <span class="cm-def">f</span>;
<span class="cm-variable">f</span> <span class="cm-operator">=</span> <span class="cm-keyword">function</span>(<span class="cm-def">a</span> <span class="cm-operator">=</span> <span class="cm-number">1</span>) {
<span class="cm-keyword">return</span> <span class="cm-variable-2">a</span>;
};
<span class="cm-variable">f</span>(<span class="cm-atom">null</span>); <span class="cm-comment">// Returns 1 in CoffeeScript 1.x, null in CoffeeScript 2</span>
</pre>
</div>
</div>
<div class="row">
<div class="col text-right">
<button type="button" class="btn btn-primary" data-action="run-code-example" data-example="breaking_change_function_parameter_default_values" data-run="f%28null%29"><small><svg class="play-button" viewBox="0 0 24 24">
<path d="M2.56-0.01v24.02L21.44 11.98 2.56-0.01z"></path>
</svg>
</small>f(null)</button>
</div>
</div>
</aside>
<aside class="code-example container-fluid bg-ribbed-dark" data-example="breaking_change_destructuring_default_values">
<div class="row">
<div class="col-md-6 coffeescript-input-column">
<textarea class="coffeescript-input" id="breaking_change_destructuring_default_values-coffee">{a = 1} = {a: null}
a # Equals 1 in CoffeeScript 1.x, null in CoffeeScript 2
</textarea>
<pre class="placeholder-code"><span class="cm-punctuation">{</span><span class="cm-variable">a</span> <span class="cm-punctuation">=</span> <span class="cm-number">1</span><span class="cm-punctuation">}</span> <span class="cm-punctuation">=</span> <span class="cm-punctuation">{</span><span class="cm-variable">a</span><span class="cm-punctuation">:</span> <span class="cm-atom">null</span><span class="cm-punctuation">}</span>
<span class="cm-variable">a</span> <span class="cm-comment"># Equals 1 in CoffeeScript 1.x, null in CoffeeScript 2</span>
</pre>
</div>
<div class="col-md-6 javascript-output-column">
<textarea class="javascript-output" id="breaking_change_destructuring_default_values-js">var a;
({a = 1} = {
a: null
});
a; // Equals 1 in CoffeeScript 1.x, null in CoffeeScript 2
</textarea>
<pre class="placeholder-code"><span class="cm-keyword">var</span> <span class="cm-def">a</span>;
({<span class="cm-property">a</span> <span class="cm-operator">=</span> <span class="cm-number">1</span>} <span class="cm-operator">=</span> {
<span class="cm-property">a</span>: <span class="cm-atom">null</span>
});
<span class="cm-variable">a</span>; <span class="cm-comment">// Equals 1 in CoffeeScript 1.x, null in CoffeeScript 2</span>
</pre>
</div>
</div>
<div class="row">
<div class="col text-right">
<button type="button" class="btn btn-primary" data-action="run-code-example" data-example="breaking_change_destructuring_default_values" data-run="a"><small><svg class="play-button" viewBox="0 0 24 24">
<path d="M2.56-0.01v24.02L21.44 11.98 2.56-0.01z"></path>
</svg>
</small>a</button>
</div>
</div>
</aside>
</section>
<section id="breaking-changes-bound-generator-functions">
<h3>Bound generator functions</h3>
<p>Bound generator functions, a.k.a. generator arrow functions, <a href="http://stackoverflow.com/questions/27661306/can-i-use-es6s-arrow-function-syntax-with-generators-arrow-notation">arent allowed in ECMAScript</a>. You can write <code>function*</code> or <code>=&gt;</code>, but not both. Therefore, CoffeeScript code like this:</p>
<blockquote class="uneditable-code-block"><pre><code class="language-coffee"><span class="function"><span class="title">f</span> = =&gt;</span> <span class="keyword">yield</span> <span class="keyword">this</span>
<span class="comment"># Throws a compiler error</span>
</code></pre>
</blockquote><p>Needs to be rewritten the old-fashioned way:</p>
<aside class="code-example container-fluid bg-ribbed-dark" data-example="breaking_change_bound_generator_function">
<div class="row">
<div class="col-md-6 coffeescript-input-column">
<textarea class="coffeescript-input" id="breaking_change_bound_generator_function-coffee">self = this
f = -> yield self
</textarea>
<pre class="placeholder-code"><span class="cm-variable">self</span> <span class="cm-punctuation">=</span> <span class="cm-keyword">this</span>
<span class="cm-variable">f</span> <span class="cm-punctuation">=</span> <span class="cm-operator">-></span> <span class="cm-variable">yield</span> <span class="cm-variable">self</span>
</pre>
</div>
<div class="col-md-6 javascript-output-column">
<textarea class="javascript-output" id="breaking_change_bound_generator_function-js">var f, self;
self = this;
f = function*() {
return (yield self);
};
</textarea>
<pre class="placeholder-code"><span class="cm-keyword">var</span> <span class="cm-def">f</span>, <span class="cm-def">self</span>;
<span class="cm-variable">self</span> <span class="cm-operator">=</span> <span class="cm-keyword">this</span>;
<span class="cm-variable">f</span> <span class="cm-operator">=</span> <span class="cm-keyword">function*</span>() {
<span class="cm-keyword">return</span> (<span class="cm-keyword">yield</span> <span class="cm-variable">self</span>);
};
</pre>
</div>
</div>
</aside>
</section>
<section id="breaking-changes-classes">
<h3>Classes are compiled to ES2015 classes</h3>
<p>ES2015 classes and their methods have some restrictions beyond those on regular functions.</p>
<p>Class constructors cant be invoked without <code>new</code>:</p>
<blockquote class="uneditable-code-block"><pre><code class="language-coffee">(<span class="class"><span class="keyword">class</span>)()</span>
<span class="comment"># Throws a TypeError at runtime</span>
</code></pre>
</blockquote><p>ES2015 classes dont allow bound (fat arrow) methods. The CoffeeScript compiler goes through some contortions to preserve support for them, but one thing that cant be accommodated is calling a bound method before it is bound:</p>
<blockquote class="uneditable-code-block"><pre><code class="language-coffee"><span class="class"><span class="keyword">class</span> <span class="title">Base</span></span>
constructor: <span class="function">-&gt;</span>
@onClick() <span class="comment"># This works</span>
clickHandler = @onClick
clickHandler() <span class="comment"># This throws a runtime error</span>
<span class="class"><span class="keyword">class</span> <span class="title">Component</span> <span class="keyword">extends</span> <span class="title">Base</span></span>
onClick: <span class="function">=&gt;</span>
<span class="built_in">console</span>.log <span class="string">'Clicked!'</span>, @
</code></pre>
</blockquote><p>Class methods cant be used with <code>new</code> (uncommon):</p>
<blockquote class="uneditable-code-block"><pre><code class="language-coffee"><span class="class"><span class="keyword">class</span> <span class="title">Namespace</span></span>
@Klass = <span class="function">-&gt;</span>
<span class="keyword">new</span> Namespace.Klass <span class="comment"># Throws a TypeError at runtime</span>
</code></pre>
</blockquote><p>Due to the hoisting required to compile to ES2015 classes, dynamic keys in class methods cant use values from the executable class body unless the methods are assigned in prototype style.</p>
<blockquote class="uneditable-code-block"><pre><code class="language-coffee"><span class="class"><span class="keyword">class</span> <span class="title">A</span></span>
name = <span class="string">'method'</span>
<span class="string">"<span class="subst">#{name}</span>"</span>: <span class="function">-&gt;</span> <span class="comment"># This method will be named 'undefined'</span>
@::[name] = <span class="function">-&gt;</span> <span class="comment"># This will work; assigns to `A.prototype.method`</span>
</code></pre>
</blockquote>
</section>
<section id="breaking-changes-super-this">
<h3><code>super</code> and <code>this</code></h3>
<p>In the constructor of a derived class (a class that <code>extends</code> another class), <code>this</code> cannot be used before calling <code>super</code>:</p>
<blockquote class="uneditable-code-block"><pre><code class="language-coffee"><span class="class"><span class="keyword">class</span> <span class="title">B</span> <span class="keyword">extends</span> <span class="title">A</span></span>
constructor: <span class="function">-&gt;</span> <span class="keyword">this</span> <span class="comment"># Throws a compiler error</span>
</code></pre>
</blockquote><p>This also means you cannot pass a reference to <code>this</code> as an argument to <code>super</code> in the constructor of a derived class:</p>
<blockquote class="uneditable-code-block"><pre><code class="language-coffee"><span class="class"><span class="keyword">class</span> <span class="title">B</span> <span class="keyword">extends</span> <span class="title">A</span></span>
constructor: <span class="function"><span class="params">(@arg)</span> -&gt;</span>
<span class="keyword">super</span> @arg <span class="comment"># Throws a compiler error</span>
</code></pre>
</blockquote><p>This is a limitation of ES2015 classes. As a workaround, assign to <code>this</code> after the <code>super</code> call:</p>
<aside class="code-example container-fluid bg-ribbed-dark" data-example="breaking_change_super_this">
<div class="row">
<div class="col-md-6 coffeescript-input-column">
<textarea class="coffeescript-input" id="breaking_change_super_this-coffee">class B extends A
constructor: (arg) ->
super arg
@arg = arg
</textarea>
<pre class="placeholder-code"><span class="cm-keyword">class</span> <span class="cm-variable">B</span> <span class="cm-keyword">extends</span> <span class="cm-variable">A</span>
<span class="cm-variable">constructor</span><span class="cm-punctuation">:</span> <span class="cm-punctuation">(</span><span class="cm-variable">arg</span><span class="cm-punctuation">)</span> <span class="cm-operator">-></span>
<span class="cm-variable">super</span> <span class="cm-variable">arg</span>
<span class="cm-property">@arg</span> <span class="cm-punctuation">=</span> <span class="cm-variable">arg</span>
</pre>
</div>
<div class="col-md-6 javascript-output-column">
<textarea class="javascript-output" id="breaking_change_super_this-js">var B;
B = class B extends A {
constructor(arg) {
super(arg);
this.arg = arg;
}
};
</textarea>
<pre class="placeholder-code"><span class="cm-keyword">var</span> <span class="cm-def">B</span>;
<span class="cm-variable">B</span> <span class="cm-operator">=</span> <span class="cm-keyword">class</span> <span class="cm-def">B</span> <span class="cm-keyword">extends</span> <span class="cm-variable">A</span> {
<span class="cm-property">constructor</span>(<span class="cm-def">arg</span>) {
<span class="cm-keyword">super</span>(<span class="cm-variable-2">arg</span>);
<span class="cm-keyword">this</span>.<span class="cm-property">arg</span> <span class="cm-operator">=</span> <span class="cm-variable-2">arg</span>;
}
};
</pre>
</div>
</div>
</aside>
</section>
<section id="breaking-changes-super-extends">
<h3><code>super</code> and <code>extends</code></h3>
<p>Due to a syntax clash with <code>super</code> with accessors, “bare” <code>super</code> (the keyword <code>super</code> without parentheses) no longer compiles to a super call forwarding all arguments.</p>
<blockquote class="uneditable-code-block"><pre><code class="language-coffee"><span class="class"><span class="keyword">class</span> <span class="title">B</span> <span class="keyword">extends</span> <span class="title">A</span></span>
foo: <span class="function">-&gt;</span> <span class="keyword">super</span>
<span class="comment"># Throws a compiler error</span>
</code></pre>
</blockquote><p>Arguments can be forwarded explicitly using splats:</p>
<aside class="code-example container-fluid bg-ribbed-dark" data-example="breaking_change_super_with_arguments">
<div class="row">
<div class="col-md-6 coffeescript-input-column">
<textarea class="coffeescript-input" id="breaking_change_super_with_arguments-coffee">class B extends A
foo: -> super arguments...
</textarea>
<pre class="placeholder-code"><span class="cm-keyword">class</span> <span class="cm-variable">B</span> <span class="cm-keyword">extends</span> <span class="cm-variable">A</span>
<span class="cm-variable">foo</span><span class="cm-punctuation">:</span> <span class="cm-operator">-></span> <span class="cm-variable">super</span> <span class="cm-variable">arguments</span><span class="cm-punctuation">...</span>
</pre>
</div>
<div class="col-md-6 javascript-output-column">
<textarea class="javascript-output" id="breaking_change_super_with_arguments-js">var B;
B = class B extends A {
foo() {
return super.foo(...arguments);
}
};
</textarea>
<pre class="placeholder-code"><span class="cm-keyword">var</span> <span class="cm-def">B</span>;
<span class="cm-variable">B</span> <span class="cm-operator">=</span> <span class="cm-keyword">class</span> <span class="cm-def">B</span> <span class="cm-keyword">extends</span> <span class="cm-variable">A</span> {
<span class="cm-property">foo</span>() {
<span class="cm-keyword">return</span> <span class="cm-keyword">super</span>.<span class="cm-property">foo</span>(<span class="cm-meta">...</span><span class="cm-variable-2">arguments</span>);
}
};
</pre>
</div>
</div>
</aside>
<p>Or if you know that the parent function doesnt require arguments, just call <code>super()</code>:</p>
<aside class="code-example container-fluid bg-ribbed-dark" data-example="breaking_change_super_without_arguments">
<div class="row">
<div class="col-md-6 coffeescript-input-column">
<textarea class="coffeescript-input" id="breaking_change_super_without_arguments-coffee">class B extends A
foo: -> super()
</textarea>
<pre class="placeholder-code"><span class="cm-keyword">class</span> <span class="cm-variable">B</span> <span class="cm-keyword">extends</span> <span class="cm-variable">A</span>
<span class="cm-variable">foo</span><span class="cm-punctuation">:</span> <span class="cm-operator">-></span> <span class="cm-variable">super</span><span class="cm-punctuation">()</span>
</pre>
</div>
<div class="col-md-6 javascript-output-column">
<textarea class="javascript-output" id="breaking_change_super_without_arguments-js">var B;
B = class B extends A {
foo() {
return super.foo();
}
};
</textarea>
<pre class="placeholder-code"><span class="cm-keyword">var</span> <span class="cm-def">B</span>;
<span class="cm-variable">B</span> <span class="cm-operator">=</span> <span class="cm-keyword">class</span> <span class="cm-def">B</span> <span class="cm-keyword">extends</span> <span class="cm-variable">A</span> {
<span class="cm-property">foo</span>() {
<span class="cm-keyword">return</span> <span class="cm-keyword">super</span>.<span class="cm-property">foo</span>();
}
};
</pre>
</div>
</div>
</aside>
<p>CoffeeScript 1.x allowed the <code>extends</code> keyword to set up prototypal inheritance between functions, and <code>super</code> could be used manually prototype-assigned functions:</p>
<blockquote class="uneditable-code-block"><pre><code class="language-coffee"><span class="function"><span class="title">A</span> = -&gt;</span>
<span class="function"><span class="title">B</span> = -&gt;</span>
B extends A
B.prototype.foo = <span class="function">-&gt;</span> <span class="keyword">super</span> arguments...
<span class="comment"># Last two lines each throw compiler errors in CoffeeScript 2</span>
</code></pre>
</blockquote><p>Due to the switch to ES2015 <code>extends</code> and <code>super</code>, using these keywords for prototypal functions are no longer supported. The above case could be refactored to:</p>
<aside class="code-example container-fluid bg-ribbed-dark" data-example="breaking_change_super_in_non-class_methods_refactor_with_apply">
<div class="row">
<div class="col-md-6 coffeescript-input-column">
<textarea class="coffeescript-input" id="breaking_change_super_in_non-class_methods_refactor_with_apply-coffee"># Helper functions
hasProp = {}.hasOwnProperty
extend = (child, parent) ->
ctor = ->
@constructor = child
return
for key of parent
if hasProp.call(parent, key)
child[key] = parent[key]
ctor.prototype = parent.prototype
child.prototype = new ctor
child
A = ->
B = ->
extend B, A
B.prototype.foo = -> A::foo.apply this, arguments
</textarea>
<pre class="placeholder-code"><span class="cm-comment"># Helper functions</span>
<span class="cm-variable">hasProp</span> <span class="cm-punctuation">=</span> <span class="cm-punctuation">{}.</span><span class="cm-property">hasOwnProperty</span>
<span class="cm-variable">extend</span> <span class="cm-punctuation">=</span> <span class="cm-punctuation">(</span><span class="cm-variable">child</span><span class="cm-punctuation">,</span> <span class="cm-variable">parent</span><span class="cm-punctuation">)</span> <span class="cm-operator">-></span>
<span class="cm-variable">ctor</span> <span class="cm-punctuation">=</span> <span class="cm-operator">-></span>
<span class="cm-property">@constructor</span> <span class="cm-punctuation">=</span> <span class="cm-variable">child</span>
<span class="cm-keyword">return</span>
<span class="cm-keyword">for</span> <span class="cm-variable">key</span> <span class="cm-keyword">of</span> <span class="cm-variable">parent</span>
<span class="cm-keyword">if</span> <span class="cm-variable">hasProp</span><span class="cm-punctuation">.</span><span class="cm-property">call</span><span class="cm-punctuation">(</span><span class="cm-variable">parent</span><span class="cm-punctuation">,</span> <span class="cm-variable">key</span><span class="cm-punctuation">)</span>
<span class="cm-variable">child</span><span class="cm-punctuation">[</span><span class="cm-variable">key</span><span class="cm-punctuation">]</span> <span class="cm-punctuation">=</span> <span class="cm-variable">parent</span><span class="cm-punctuation">[</span><span class="cm-variable">key</span><span class="cm-punctuation">]</span>
<span class="cm-dedent"> </span><span class="cm-variable">ctor</span><span class="cm-punctuation">.</span><span class="cm-property">prototype</span> <span class="cm-punctuation">=</span> <span class="cm-variable">parent</span><span class="cm-punctuation">.</span><span class="cm-property">prototype</span>
<span class="cm-variable">child</span><span class="cm-punctuation">.</span><span class="cm-property">prototype</span> <span class="cm-punctuation">=</span> <span class="cm-keyword">new</span> <span class="cm-variable">ctor</span>
<span class="cm-variable">child</span>
<span class="cm-variable">A</span> <span class="cm-punctuation">=</span> <span class="cm-operator">-></span>
<span class="cm-variable">B</span> <span class="cm-punctuation">=</span> <span class="cm-operator">-></span>
<span class="cm-variable">extend</span> <span class="cm-variable">B</span><span class="cm-punctuation">,</span> <span class="cm-variable">A</span>
<span class="cm-variable">B</span><span class="cm-punctuation">.</span><span class="cm-property">prototype</span><span class="cm-punctuation">.</span><span class="cm-property">foo</span> <span class="cm-punctuation">=</span> <span class="cm-operator">-></span> <span class="cm-variable">A</span><span class="cm-punctuation">::</span><span class="cm-variable">foo</span><span class="cm-punctuation">.</span><span class="cm-property">apply</span> <span class="cm-keyword">this</span><span class="cm-punctuation">,</span> <span class="cm-variable">arguments</span>
</pre>
</div>
<div class="col-md-6 javascript-output-column">
<textarea class="javascript-output" id="breaking_change_super_in_non-class_methods_refactor_with_apply-js">// Helper functions
var A, B, extend, hasProp;
hasProp = {}.hasOwnProperty;
extend = function(child, parent) {
var ctor, key;
ctor = function() {
this.constructor = child;
};
for (key in parent) {
if (hasProp.call(parent, key)) {
child[key] = parent[key];
}
}
ctor.prototype = parent.prototype;
child.prototype = new ctor;
return child;
};
A = function() {};
B = function() {};
extend(B, A);
B.prototype.foo = function() {
return A.prototype.foo.apply(this, arguments);
};
</textarea>
<pre class="placeholder-code"><span class="cm-comment">// Helper functions</span>
<span class="cm-keyword">var</span> <span class="cm-def">A</span>, <span class="cm-def">B</span>, <span class="cm-def">extend</span>, <span class="cm-def">hasProp</span>;
<span class="cm-variable">hasProp</span> <span class="cm-operator">=</span> {}.<span class="cm-property">hasOwnProperty</span>;
<span class="cm-variable">extend</span> <span class="cm-operator">=</span> <span class="cm-keyword">function</span>(<span class="cm-def">child</span>, <span class="cm-def">parent</span>) {
<span class="cm-keyword">var</span> <span class="cm-def">ctor</span>, <span class="cm-def">key</span>;
<span class="cm-variable-2">ctor</span> <span class="cm-operator">=</span> <span class="cm-keyword">function</span>() {
<span class="cm-keyword">this</span>.<span class="cm-property">constructor</span> <span class="cm-operator">=</span> <span class="cm-variable-2">child</span>;
};
<span class="cm-keyword">for</span> (<span class="cm-variable-2">key</span> <span class="cm-keyword">in</span> <span class="cm-variable-2">parent</span>) {
<span class="cm-keyword">if</span> (<span class="cm-variable">hasProp</span>.<span class="cm-property">call</span>(<span class="cm-variable-2">parent</span>, <span class="cm-variable-2">key</span>)) {
<span class="cm-variable-2">child</span>[<span class="cm-variable-2">key</span>] <span class="cm-operator">=</span> <span class="cm-variable-2">parent</span>[<span class="cm-variable-2">key</span>];
}
}
<span class="cm-variable-2">ctor</span>.<span class="cm-property">prototype</span> <span class="cm-operator">=</span> <span class="cm-variable-2">parent</span>.<span class="cm-property">prototype</span>;
<span class="cm-variable-2">child</span>.<span class="cm-property">prototype</span> <span class="cm-operator">=</span> <span class="cm-keyword">new</span> <span class="cm-variable-2">ctor</span>;
<span class="cm-keyword">return</span> <span class="cm-variable-2">child</span>;
};
<span class="cm-variable">A</span> <span class="cm-operator">=</span> <span class="cm-keyword">function</span>() {};
<span class="cm-variable">B</span> <span class="cm-operator">=</span> <span class="cm-keyword">function</span>() {};
<span class="cm-variable">extend</span>(<span class="cm-variable">B</span>, <span class="cm-variable">A</span>);
<span class="cm-variable">B</span>.<span class="cm-property">prototype</span>.<span class="cm-property">foo</span> <span class="cm-operator">=</span> <span class="cm-keyword">function</span>() {
<span class="cm-keyword">return</span> <span class="cm-variable">A</span>.<span class="cm-property">prototype</span>.<span class="cm-property">foo</span>.<span class="cm-property">apply</span>(<span class="cm-keyword">this</span>, <span class="cm-variable-2">arguments</span>);
};
</pre>
</div>
</div>
</aside>
<p>or</p>
<aside class="code-example container-fluid bg-ribbed-dark" data-example="breaking_change_super_in_non-class_methods_refactor_with_class">
<div class="row">
<div class="col-md-6 coffeescript-input-column">
<textarea class="coffeescript-input" id="breaking_change_super_in_non-class_methods_refactor_with_class-coffee">class A
class B extends A
foo: -> super arguments...
</textarea>
<pre class="placeholder-code"><span class="cm-keyword">class</span> <span class="cm-variable">A</span>
<span class="cm-keyword">class</span> <span class="cm-variable">B</span> <span class="cm-keyword">extends</span> <span class="cm-variable">A</span>
<span class="cm-variable">foo</span><span class="cm-punctuation">:</span> <span class="cm-operator">-></span> <span class="cm-variable">super</span> <span class="cm-variable">arguments</span><span class="cm-punctuation">...</span>
</pre>
</div>
<div class="col-md-6 javascript-output-column">
<textarea class="javascript-output" id="breaking_change_super_in_non-class_methods_refactor_with_class-js">var A, B;
A = class A {};
B = class B extends A {
foo() {
return super.foo(...arguments);
}
};
</textarea>
<pre class="placeholder-code"><span class="cm-keyword">var</span> <span class="cm-def">A</span>, <span class="cm-def">B</span>;
<span class="cm-variable">A</span> <span class="cm-operator">=</span> <span class="cm-keyword">class</span> <span class="cm-def">A</span> {};
<span class="cm-variable">B</span> <span class="cm-operator">=</span> <span class="cm-keyword">class</span> <span class="cm-def">B</span> <span class="cm-keyword">extends</span> <span class="cm-variable">A</span> {
<span class="cm-property">foo</span>() {
<span class="cm-keyword">return</span> <span class="cm-keyword">super</span>.<span class="cm-property">foo</span>(<span class="cm-meta">...</span><span class="cm-variable-2">arguments</span>);
}
};
</pre>
</div>
</div>
</aside>
</section>
<section id="breaking-changes-jsx-and-the-less-than-and-greater-than-operators">
<h3>JSX and the <code>&lt;</code> and <code>&gt;</code> operators</h3>
<p>With the addition of <a href="#jsx">JSX</a>, the <code>&lt;</code> and <code>&gt;</code> characters serve as both the “less than” and “greater than” operators and as the delimiters for XML tags, like <code>&lt;div&gt;</code>. For best results, in general you should always wrap the operators in spaces to distinguish them from XML tags: <code>i &lt; len</code>, not <code>i&lt;len</code>. The compiler tries to be forgiving when it can be sure what you intend, but always putting spaces around the “less than” and “greater than” operators will remove ambiguity.</p>
</section>
<section id="breaking-changes-literate-coffeescript">
<h3>Literate CoffeeScript parsing</h3>
<p>CoffeeScript 2s parsing of Literate CoffeeScript has been refactored to now be more careful about not treating indented lists as code blocks; but this means that all code blocks (unless they are to be interpreted as comments) must be separated by at least one blank line from lists.</p>
<p>Code blocks should also now maintain a consistent indentation level—so an indentation of one tab (or whatever you consider to be a tab stop, like 2 spaces or 4 spaces) should be treated as your codes “left margin,” with all code in the file relative to that column.</p>
<p>Code blocks that you want to be part of the commentary, and not executed, must have at least one line (ideally the first line of the block) completely unindented.</p>
</section>
<section id="breaking-changes-argument-parsing-and-shebang-lines">
<h3>Argument parsing and shebang (<code>#!</code>) lines</h3>
<p>In CoffeeScript 1.x, <code>--</code> was required after the path and filename of the script to be run, but before any arguments passed to that script. This convention is now deprecated. So instead of:</p>
<blockquote class="uneditable-code-block"><pre><code class="language-bash">coffee [options] path/to/script.coffee -- [args]
</code></pre>
</blockquote><p>Now you would just type:</p>
<blockquote class="uneditable-code-block"><pre><code class="language-bash">coffee [options] path/to/script.coffee [args]
</code></pre>
</blockquote><p>The deprecated version will still work, but it will print a warning before running the script.</p>
<p>On non-Windows platforms, a <code>.coffee</code> file can be made executable by adding a shebang (<code>#!</code>) line at the top of the file and marking the file as executable. For example:</p>
<blockquote class="uneditable-code-block"><pre><code class="language-coffee"><span class="comment">#!/usr/bin/env coffee</span>
x = <span class="number">2</span> + <span class="number">2</span>
<span class="built_in">console</span>.log x
</code></pre>
</blockquote><p>If this were saved as <code>executable.coffee</code>, it could be made executable and run:</p>
<blockquote class="uneditable-code-block"><pre><code class="language-bash">▶ chmod +x ./executable.coffee
▶ ./executable.coffee
4
</code></pre>
</blockquote><p>In CoffeeScript 1.x, this used to fail when trying to pass arguments to the script. Some users on OS X worked around the problem by using <code>#!/usr/bin/env coffee --</code> as the first line of the file. That didnt work on Linux, however, which cannot parse shebang lines with more than a single argument. While such scripts will still run on OS X, CoffeeScript will now display a warning before compiling or evaluating files that begin with a too-long shebang line. Now that CoffeeScript 2 supports passing arguments without needing <code>--</code>, we recommend simply changing the shebang lines in such scripts to just <code>#!/usr/bin/env coffee</code>.</p>
</section>
</section>
<section id="changelog">
<h2>Changelog</h2>
<section id="2.3.1">
<h3><a href="https://github.com/jashkenas/coffeescript/compare/2.3.0...2.3.1">2.3.1</a>
<span class="timestamp"> &mdash; <time datetime="2018-05-21">2018-05-21</time></span>
</h3><ul>
<li>Returning a JSX tag that is adjacent to another JSX tag, as opposed to returning a root JSX tag or fragment, is invalid JSX syntax. Babel throws an error on this, and now the CoffeeScript compiler does too.</li>
<li>Invalid indentation inside a JSX interpolation (the middle of <code>&lt;tag&gt;{ ... }&lt;/tag&gt;</code>) now throws an error.</li>
<li>The browser compiler, used in <a href="https://coffeescript.org/#try">Try CoffeeScript</a> and similar web-based CoffeeScript editors, now evaluates code in a global scope rather than the scope of the browser compiler. This improves performance of code executed via the browser compiler.</li>
<li>Syntax cleanup: it is now possible for an implicit function call to take a body-less class as an argument, and <code>?::</code> now behaves identically to <code>::</code> with regard to implying a line continuation.</li>
</ul>
</section>
<section id="2.3.0">
<h3><a href="https://github.com/jashkenas/coffeescript/compare/2.2.4...2.3.0">2.3.0</a>
<span class="timestamp"> &mdash; <time datetime="2018-04-29">2018-04-29</time></span>
</h3><ul>
<li>This release adds support for all the new features and syntaxes in ES2018 that werent already possible in CoffeeScript. For all of the below features, make sure that you <a href="#transpilation">transpile</a> unless you know that your target runtime(s) support each feature.</li>
<li>Asynchronous iterators are now supported. You can now <code>yield</code> an <code>await</code> call, e.g. <code>do -&gt; until file.EOF then yield await file.readLine()</code>.</li>
<li>Object splats/destructuring, a.k.a. object rest/spread syntax, has been standardized as part of ES2018 and therefore this release removes the polyfill that had previously been supporting this syntax. Code like <code>{a, b, rest...} = obj</code> now outputs more or less just like it appears, rather than being converted into an <code>Object.assign</code> call. Note that there are <a href="https://developers.google.com/web/updates/2017/06/object-rest-spread">some subtle differences</a> between the <code>Object.assign</code> polyfill and the native implementation.</li>
<li>The exponentiation operator, <code>**</code>, and exponentiation assignment operator <code>**=</code> are new to JavaScript in ES2018. Now code like <code>a ** 3</code> is output as it appears, rather than being converted into <code>Math.pow(a, 3)</code> as it was before.</li>
<li>The <code>s</code> (dotAll) flag is now supported in regular expressions.</li>
</ul>
</section>
<section id="2.2.4">
<h3><a href="https://github.com/jashkenas/coffeescript/compare/2.2.3...2.2.4">2.2.4</a>
<span class="timestamp"> &mdash; <time datetime="2018-03-29">2018-03-29</time></span>
</h3><ul>
<li>When the <code>by</code> value in a <code>for</code> loop is a literal number, e.g. <code>for x in [2..1] by -1</code>, fewer checks are necessary to determine if the loop is in range.</li>
<li>Bugfix for regression in 2.2.0 where a statement inside parentheses, e.g. <code>(fn(); break) while condition</code>, was compiling. Pure statements like <code>break</code> or <code>return</code> cannot turn a parenthesized block into an expression, and should throw an error.</li>
</ul>
</section>
<section id="2.2.3">
<h3><a href="https://github.com/jashkenas/coffeescript/compare/2.2.2...2.2.3">2.2.3</a>
<span class="timestamp"> &mdash; <time datetime="2018-03-11">2018-03-11</time></span>
</h3><ul>
<li>Bugfix for object destructuring with an empty array as a keys value: <code>{ key: [] } = obj</code>.</li>
<li>Bugfix for array destructuring onto targets attached to <code>this</code>: <code>[ @most... , @penultimate, @last ] = arr</code>.</li>
</ul>
</section>
<section id="2.2.2">
<h3><a href="https://github.com/jashkenas/coffeescript/compare/2.2.1...2.2.2">2.2.2</a>
<span class="timestamp"> &mdash; <time datetime="2018-02-21">2018-02-21</time></span>
</h3><ul>
<li>Bugfix for regression in 2.2.0 where a range with a <code>by</code> (step) value that increments or decrements in the opposite direction as the range was returning an array containing the first value of the range, whereas it should be returning an empty array. In other words, <code>x for x in [2..1] by 1</code> should equal <code>[]</code>, not <code>[2]</code> (because the step value is positive 1, counting up, whereas the range goes from 2 to 1, counting down).</li>
<li>Bugfixes for allowing backslashes in <code>import</code> and <code>export</code> statements and lines that trigger the start of an indented block, like an <code>if</code> statement.</li>
</ul>
</section>
<section id="2.2.1">
<h3><a href="https://github.com/jashkenas/coffeescript/compare/2.2.0...2.2.1">2.2.1</a>
<span class="timestamp"> &mdash; <time datetime="2018-02-06">2018-02-06</time></span>
</h3><ul>
<li>Bugfix for regression in 2.2.0 involving an error thrown by the compiler in certain cases when using destructuring with a splat or expansion in an array.</li>
<li>Bugfix for regression in 2.2.0 where in certain cases a range iterator variable was declared in the global scope.</li>
</ul>
</section>
<section id="2.2.0">
<h3><a href="https://github.com/jashkenas/coffeescript/compare/2.1.1...2.2.0">2.2.0</a>
<span class="timestamp"> &mdash; <time datetime="2018-02-01">2018-02-01</time></span>
</h3><ul>
<li>This release fixes <em>all</em> currently open bugs, dating as far back as 2014, 2012 and 2011.</li>
<li><strong>Potential breaking change:</strong> An inline <code>if</code> or <code>switch</code> statement with an ambiguous <code>else</code>, such as <code>if no then if yes then alert 1 else alert 2</code>, now compiles where the <code>else</code> always corresponds to the closest open <code>then</code>. Previously the behavior of an ambiguous <code>else</code> was unpredictable. If your code has any <code>if … then</code> or <code>switch … then</code> statements with multiple <code>then</code>s (and one or more <code>else</code>s) the compiled output might be different now, unless you had resolved ambiguity via parentheses. We made this change because the previous behavior was inconsistent and basically a bug: depending on what grammar was where, for example if there was an inline function or something that implied a block, the <code>else</code> might bind to an earlier <code>then</code> rather than a later <code>then</code>. Now an <code>else</code> essentially closes a block opened by a <code>then</code>, similar to closing an open parenthesis.</li>
<li>When a required <code>then</code> is missing, the error more accurately points out the location of the mistake.</li>
<li>An error is thrown when the <code>coffee</code> command is run in an environment that doesnt support some ES2015 JavaScript features that the CoffeeScript compiler itself requires. This can happen if CoffeeScript is installed in Node older than version 6.</li>
<li>Destructuring with a non-final splat/spread, e.g. <code>[open, contents..., close] = tag.split('')</code> is now output using ES2015 rest syntax.</li>
<li>Functions named <code>get</code> or <code>set</code> can be used without parentheses in more cases, including when attached to <code>this</code> or <code>@</code> or <code>?.</code>; or when the first argument is an implicit object, e.g. <code>@set key: 'val'</code>.</li>
<li>Statements such as <code>break</code> can now be used inside parentheses, e.g. <code>(doSomething(); break) while condition</code> or <code>(pick(key); break) for key of obj</code>.</li>
<li>Bugfix for assigning to a property attached to <code>this</code>/<code>@</code> in destructuring, e.g. <code>({@prop = yes, @otherProp = no}) -&gt;</code>.</li>
<li>Bugfix for incorrect errors being thrown about calling <code>super</code> with a parameter attached to <code>this</code> when said parameter is in a lower scope, e.g. <code>class Child extends Parent then constructor: -&gt; super(-&gt; @prop)</code>.</li>
<li>Bugfix to prevent a possible infinite loop when a <code>for</code> loop is given a variable to step by, e.g. <code>for x in [1..3] by step</code> (as opposed to <code>by 0.5</code> or some other primitive numeric value).</li>
<li>Bugfix to no longer declare iterator variables twice when evaluating a range, e.g. <code>end = 3; fn [0..end]</code>.</li>
<li>Bugfix for incorrect scope of variables in chained calls, e.g. <code>start(x = 3).then(-&gt; x = 4)</code>.</li>
<li>Bugfix for incorrect scope of variables in a function passed to <code>do</code>, e.g. <code>for [1..3] then masked = 10; do -&gt; alert masked</code>.</li>
<li>Bugfix to no longer throw a syntax error for a trailing comma in a function call, e.g. <code>fn arg1, arg2,</code>.</li>
<li>Bugfix for an expression in a property access, e.g. <code>a[!b in c..]</code>.</li>
<li>Bugfix to allow a line continuation backslash (<code>\</code>) at any point in a <code>for</code> line.</li>
</ul>
</section>
<section id="2.1.1">
<h3><a href="https://github.com/jashkenas/coffeescript/compare/2.1.0...2.1.1">2.1.1</a>
<span class="timestamp"> &mdash; <time datetime="2017-12-29">2017-12-29</time></span>
</h3><ul>
<li>Bugfix to set the correct context for executable class bodies. So in <code>class @B extends @A then @property = 1</code>, the <code>@</code> in <code>@property</code> now refers to the class, not the global object.</li>
<li>Bugfix where anonymous classes were getting created using the same automatic variable name. They now each receive unique names, so as not to override each other.</li>
</ul>
</section>
<section id="2.1.0">
<h3><a href="https://github.com/jashkenas/coffeescript/compare/2.0.3...2.1.0">2.1.0</a>
<span class="timestamp"> &mdash; <time datetime="2017-12-10">2017-12-10</time></span>
</h3><ul>
<li>Computed property keys in object literals are now supported: <code>obj = { ['key' + i]: 42 }</code>, or <code>obj = [Symbol.iterator]: -&gt; yield i++</code>.</li>
<li>Skipping of array elements, a.k.a. elision, is now supported: <code>arr = [a, , b]</code>, or <code>[, protocol] = url.match /^(.*):\/\//</code>.</li>
<li><a href="https://reactjs.org/blog/2017/11/28/react-v16.2.0-fragment-support.html">JSX fragments syntax</a> is now supported.</li>
<li>Bugfix where <code>///</code> within a <code>#</code> line comment inside a <code>///</code> block regex was erroneously closing the regex, rather than being treated as part of the comment.</li>
<li>Bugfix for incorrect output for object rest destructuring inside array destructuring.</li>
</ul>
</section>
<section id="2.0.3">
<h3><a href="https://github.com/jashkenas/coffeescript/compare/2.0.2...2.0.3">2.0.3</a>
<span class="timestamp"> &mdash; <time datetime="2017-11-26">2017-11-26</time></span>
</h3><ul>
<li>Bugfix for <code>export default</code> followed by an implicit object that contains an explicit object, for example <code>exportedMember: { obj... }</code>.</li>
<li>Bugfix for <code>key, val of obj</code> after an implicit object member, e.g. <code>foo: bar for key, val of obj</code>.</li>
<li>Bugfix for combining array and object destructuring, e.g. <code>[ ..., {a, b} ] = arr</code>.</li>
<li>Bugfix for an edge case where it was possible to create a bound (<code>=&gt;</code>) generator function, which should throw an error as such functions arent allowed in ES2015.</li>
<li>Bugfix for source maps: <code>.map</code> files should always have the same base filename as the requested output filename. So <code>coffee --map --output foo.js test.coffee</code> should generate <code>foo.js</code> and <code>foo.js.map</code>.</li>
<li>Bugfix for incorrect source maps generated when using <code>--transpile</code> with <code>--map</code> for multiple input files.</li>
<li>Bugfix for comments at the beginning or end of input into the REPL (<code>coffee --interactive</code>).</li>
</ul>
</section>
<section id="2.0.2">
<h3><a href="https://github.com/jashkenas/coffeescript/compare/2.0.1...2.0.2">2.0.2</a>
<span class="timestamp"> &mdash; <time datetime="2017-10-26">2017-10-26</time></span>
</h3><ul>
<li><code>--transpile</code> now also applies to <code>require</code>d or <code>import</code>ed CoffeeScript files.</li>
<li><code>--transpile</code> can be used with the REPL: <code>coffee --interactive --transpile</code>.</li>
<li>Improvements to comments output that should now cover all of the <a href="https://flow.org/en/docs/types/comments/">Flow comment-based syntax</a>. Inline <code>###</code> comments near <a href="https://flow.org/en/docs/types/variables/">variable</a> initial assignments are now output in the variable declaration statement, and <code>###</code> comments near a <a href="https://flow.org/en/docs/types/generics/">class and method names</a> are now output where Flow expects them.</li>
<li>Importing CoffeeScript keywords is now allowed, so long as theyre aliased: <code>import { and as andFn } from 'lib'</code>. (You could also do <code>import lib from 'lib'</code> and then reference <code>lib.and</code>.)</li>
<li>Calls to functions named <code>get</code> and <code>set</code> no longer throw an error when given a bracketless object literal as an argument: <code>obj.set propertyName: propertyValue</code>.</li>
<li>In the constructor of a derived class (a class that <code>extends</code> another class), you cannot call <code>super</code> with an argument that references <code>this</code>: <code>class Child extends Parent then constructor: (@arg) -&gt; super(@arg)</code>. This isnt allowed in JavaScript, and now the CoffeeScript compiler will throw an error. Instead, assign to <code>this</code> after calling <code>super</code>: <code>(arg) -&gt; super(arg); @arg = arg</code>.</li>
<li>Bugfix for incorrect output when backticked statements and hoisted expressions were both in the same class body. This allows a backticked line like <code>`field = 3`</code>, for people using the experimental <a href="https://github.com/tc39/proposal-class-fields">class fields</a> syntax, in the same class along with traditional class body expressions like <code>prop: 3</code> that CoffeeScript outputs as part of the class prototype.</li>
<li>Bugfix for comments not output before a complex <code>?</code> operation, e.g. <code>@a ? b</code>.</li>
<li>All tests now pass in Windows.</li>
</ul>
</section>
<section id="2.0.1">
<h3><a href="https://github.com/jashkenas/coffeescript/compare/2.0.0...2.0.1">2.0.1</a>
<span class="timestamp"> &mdash; <time datetime="2017-09-26">2017-09-26</time></span>
</h3><ul>
<li><code>babel-core</code> is no longer listed in <code>package.json</code>, even as an <code>optionalDependency</code>, to avoid it being automatically installed for most users. If you wish to use <code>--transpile</code>, simply install <code>babel-core</code> manually. See <a href="#transpilation">Transpilation</a>.</li>
<li><code>--transpile</code> now relies on Babel to find its options, i.e. the <code>.babelrc</code> file in the path of the file(s) being compiled. (Previously the CoffeeScript compiler was duplicating this logic, so nothing has changed from a users perspective.) This provides automatic support for additional ways to pass options to Babel in future versions, such as the <code>.babelrc.js</code> file coming in Babel 7.</li>
<li>Backticked expressions in a class body, outside any class methods, are now output in the JavaScript class body itself. This allows for passing through experimental JavaScript syntax like the <a href="https://github.com/tc39/proposal-class-fields">class fields proposal</a>, assuming your <a href="https://babeljs.io/docs/plugins/transform-class-properties/">transpiler supports it</a>.</li>
</ul>
</section>
<section id="2.0.0">
<h3><a href="https://github.com/jashkenas/coffeescript/compare/2.0.0-beta5...2.0.0">2.0.0</a>
<span class="timestamp"> &mdash; <time datetime="2017-09-18">2017-09-18</time></span>
</h3><ul>
<li>Added <code>--transpile</code> flag or <code>transpile</code> Node API option to tell the CoffeeScript compiler to pipe its output through Babel before saving or returning it; see <a href="#transpilation">Transpilation</a>. Also changed the <code>-t</code> short flag to refer to <code>--transpile</code> instead of <code>--tokens</code>.</li>
<li>Always populate source maps <code>sourcesContent</code> property.</li>
<li>Bugfixes for destructuring and for comments in JSX.</li>
<li><em>Note that these are only the changes between 2.0.0-beta5 and 2.0.0. See below for all changes since 1.x.</em></li>
</ul>
</section>
<section id="2.0.0-beta5">
<h3><a href="https://github.com/jashkenas/coffeescript/compare/2.0.0-beta4...2.0.0-beta5">2.0.0-beta5</a>
<span class="timestamp"> &mdash; <time datetime="2017-09-02">2017-09-02</time></span>
</h3><ul>
<li>Node 6 is now supported, and we will try to maintain that as the minimum required version for CoffeeScript 2 via the <code>coffee</code> command or Node API. Older versions of Node, or non-evergreen browsers, can compile via the <a href="./browser-compiler/coffeescript.js">browser compiler</a>.</li>
<li>The command line <code>--output</code> flag now allows you to specify an output filename, not just an output folder.</li>
<li>The command line <code>--require</code> flag now properly handles filenames or module names that are invalid identifiers (like an NPM module with a hyphen in the name).</li>
<li><code>Object.assign</code>, output when object destructuring is used, is polyfilled using the same polyfill that Babel outputs. This means that polyfills shouldnt be required unless support for Internet Explorer 8 or below is desired (or your own code uses a feature that requires a polyfill). See <a href="#es2015plus-output">ES2015+ Output</a>.</li>
<li>A string or JSX interpolation that contains only a comment (<code>&quot;a#{### comment ###}b&quot;</code> or <code>&lt;div&gt;{### comment ###}&lt;/div&gt;</code>) is now output (<code>`a${/* comment */}b`</code>)</li>
<li>Interpolated strings (ES2015 template literals) that contain quotation marks no longer have the quotation marks escaped: <code>`say &quot;${message}&quot;`</code></li>
<li>It is now possible to chain after a function literal (for example, to define a function and then call <code>.call</code> on it).</li>
<li>The results of the async tests are included in the output when you run <code>cake test</code>.</li>
<li>Bugfixes for object destructuring; expansions in function parameters; generated reference variables in function parameters; chained functions after <code>do</code>; splats after existential operator soaks in arrays (<code>[a?.b...]</code>); trailing <code>if</code> with splat in arrays or function parameters (<code>[a if b...]</code>); attempting to <code>throw</code> an <code>if</code>, <code>for</code>, <code>switch</code>, <code>while</code> or other invalid construct.</li>
<li>Bugfixes for syntactical edge cases: semicolons after <code>=</code> and other “mid-expression” tokens; spaces after <code>::</code>; and scripts that begin with <code>:</code> or <code>*</code>.</li>
<li>Bugfixes for source maps generated via the Node API; and stack trace line numbers when compiling CoffeeScript via the Node API from within a <code>.coffee</code> file.</li>
</ul>
</section>
<section id="2.0.0-beta4">
<h3><a href="https://github.com/jashkenas/coffeescript/compare/2.0.0-beta3...2.0.0-beta4">2.0.0-beta4</a>
<span class="timestamp"> &mdash; <time datetime="2017-08-03">2017-08-03</time></span>
</h3><ul>
<li>This release includes <a href="#1.12.7">all the changes from 1.12.6 to 1.12.7</a>.</li>
<li><a href="#comments">Line comments</a> (starting with <code>#</code>) are now output in the generated JavaScript.</li>
<li><a href="#comments">Block comments</a> (delimited by <code>###</code>) are now allowed anywhere, including inline where they previously werent possible. This provides support for <a href="#type-annotations">static type annotations</a> using Flows comments-based syntax.</li>
<li>Spread syntax (<code>...</code> for objects) is now supported in JSX tags: <code>&lt;div {props...} /&gt;</code>.</li>
<li>Argument parsing for scripts run via <code>coffee</code> is improved. See <a href="#breaking-changes-argument-parsing-and-shebang-lines">breaking changes</a>.</li>
<li>CLI: Propagate <code>SIGINT</code> and <code>SIGTERM</code> signals when node is forked.</li>
<li><code>await</code> in the REPL is now allowed without requiring a wrapper function.</li>
<li><code>do super</code> is now allowed, and other accesses of <code>super</code> like <code>super.x.y</code> or <code>super['x'].y</code> now work.</li>
<li>Splat/spread syntax triple dots are now allowed on either the left or the right (so <code>props...</code> or <code>...props</code> are both valid).</li>
<li>Tagged template literals are recognized as callable functions.</li>
<li>Bugfixes for object spread syntax in nested properties.</li>
<li>Bugfixes for destructured function parameter default values.</li>
</ul>
</section>
<section id="2.0.0-beta3">
<h3><a href="https://github.com/jashkenas/coffeescript/compare/2.0.0-beta2...2.0.0-beta3">2.0.0-beta3</a>
<span class="timestamp"> &mdash; <time datetime="2017-06-30">2017-06-30</time></span>
</h3><ul>
<li><a href="#jsx">JSX</a> is now supported.</li>
<li><a href="#object-spread">Object rest/spread properties</a> are now supported.</li>
<li>Bound (fat arrow) methods are once again supported in classes; though an error will be thrown if you attempt to call the method before it is bound. See <a href="#breaking-changes-classes">breaking changes for classes</a>.</li>
<li>The REPL no longer warns about assigning to <code>_</code>.</li>
<li>Bugfixes for destructured nested default values and issues related to chaining or continuing expressions across multiple lines.</li>
</ul>
</section>
<section id="2.0.0-beta2">
<h3><a href="https://github.com/jashkenas/coffeescript/compare/2.0.0-beta1...2.0.0-beta2">2.0.0-beta2</a>
<span class="timestamp"> &mdash; <time datetime="2017-05-16">2017-05-16</time></span>
</h3><ul>
<li>This release includes <a href="#1.12.6">all the changes from 1.12.5 to 1.12.6</a>.</li>
<li>Bound (fat arrow) methods in classes must be declared in the class constructor, after <code>super()</code> if the class is extending a parent class. See <a href="#breaking-changes-classes">breaking changes for classes</a>.</li>
<li>All unnecessary utility helper functions have been removed, including the polyfills for <code>indexOf</code> and <code>bind</code>.</li>
<li>The <code>extends</code> keyword now only works in the context of classes; it cannot be used to extend a function prototype. See <a href="#breaking-changes-super-extends">breaking changes for <code>extends</code></a>.</li>
<li>Literate CoffeeScript is now parsed entirely based on indentation, similar to the 1.x implementation; there is no longer a dependency for parsing Markdown. See <a href="#breaking-changes-literate-coffeescript">breaking changes for Literate CoffeeScript parsing</a>.</li>
<li>JavaScript reserved words used as properties are no longer wrapped in quotes.</li>
<li><code>require('coffeescript')</code> should now work in non-Node environments such as the builds created by Webpack or Browserify. This provides a more convenient way to include the browser compiler in builds intending to run in a browser environment.</li>
<li>Unreachable <code>break</code> statements are no longer added after <code>switch</code> cases that <code>throw</code> exceptions.</li>
<li>The browser compiler is now compiled using Babili and transpiled down to Babels <code>env</code> preset (should be safe for use in all browsers in current use, not just evergreen versions).</li>
<li>Calling functions <code>@get</code> or <code>@set</code> no longer throws an error about required parentheses. (Bare <code>get</code> or <code>set</code>, not attached to an object or <code>@</code>, <a href="#unsupported-get-set">still intentionally throws a compiler error</a>.)</li>
<li>If <code>$XDG_CACHE_HOME</code> is set, the REPL <code>.coffee_history</code> file is saved there.</li>
</ul>
</section>
<section id="2.0.0-beta1">
<h3><a href="https://github.com/jashkenas/coffeescript/compare/2.0.0-alpha1...2.0.0-beta1">2.0.0-beta1</a>
<span class="timestamp"> &mdash; <time datetime="2017-04-14">2017-04-14</time></span>
</h3><ul>
<li>Initial beta release of CoffeeScript 2. No further breaking changes are anticipated.</li>
<li>Destructured objects and arrays now output using ES2015+ syntax whenever possible.</li>
<li>Literate CoffeeScript now has much better support for parsing Markdown, thanks to using <a href="https://github.com/markdown-it/markdown-it">Markdown-It</a> to detect Markdown sections rather than just looking at indentation.</li>
<li>Calling a function named <code>get</code> or <code>set</code> now requires parentheses, to disambiguate from the <code>get</code> or <code>set</code> keywords (which are <a href="#unsupported-get-set">disallowed</a>).</li>
<li>The compiler now requires Node 7.6+, the first version of Node to support asynchronous functions without requiring a flag.</li>
</ul>
</section>
<section id="2.0.0-alpha1">
<h3><a href="https://github.com/jashkenas/coffeescript/compare/1.12.4...2.0.0-alpha1">2.0.0-alpha1</a>
<span class="timestamp"> &mdash; <time datetime="2017-02-21">2017-02-21</time></span>
</h3><ul>
<li>Initial alpha release of CoffeeScript 2. The CoffeeScript compiler now outputs ES2015+ syntax whenever possible. See <a href="#breaking-changes">breaking changes</a>.</li>
<li>Classes are output using ES2015 <code>class</code> and <code>extends</code> keywords.</li>
<li>Added support for <code>async</code>/<code>await</code>.</li>
<li>Bound (arrow) functions now output as <code>=&gt;</code> functions.</li>
<li>Function parameters with default values now use ES2015 default values syntax.</li>
<li>Splat function parameters now use ES2015 spread syntax.</li>
<li>Computed properties now use ES2015 syntax.</li>
<li>Interpolated strings (template literals) now use ES2015 backtick syntax.</li>
<li>Improved support for recognizing Markdown in Literate CoffeeScript files.</li>
<li>Mixing tabs and spaces in indentation is now disallowed.</li>
<li>Browser compiler is now minified using the Google Closure Compiler (JavaScript version).</li>
<li>Node 7+ required for CoffeeScript 2.</li>
</ul>
</section>
<section id="1.12.7">
<h3><a href="https://github.com/jashkenas/coffeescript/compare/1.12.6...1.12.7">1.12.7</a>
<span class="timestamp"> &mdash; <time datetime="2017-07-16">2017-07-16</time></span>
</h3><ul>
<li>Fix regressions in 1.12.6 related to chained function calls and indented <code>return</code> and <code>throw</code> arguments.</li>
<li>The REPL no longer warns about assigning to <code>_</code>.</li>
</ul>
</section>
<section id="1.12.6">
<h3><a href="https://github.com/jashkenas/coffeescript/compare/1.12.5...1.12.6">1.12.6</a>
<span class="timestamp"> &mdash; <time datetime="2017-05-15">2017-05-15</time></span>
</h3><ul>
<li>The <code>return</code> and <code>export</code> keywords can now accept implicit objects (defined by indentation, without needing braces).</li>
<li>Support Unicode code point escapes (e.g. <code>\u{1F4A9}</code>).</li>
<li>The <code>coffee</code> command now first looks to see if CoffeeScript is installed under <code>node_modules</code> in the current folder, and executes the <code>coffee</code> binary there if so; or otherwise it runs the globally installed one. This allows you to have one version of CoffeeScript installed globally and a different one installed locally for a particular project. (Likewise for the <code>cake</code> command.)</li>
<li>Bugfixes for chained function calls not closing implicit objects or ternaries.</li>
<li>Bugfixes for incorrect code generated by the <code>?</code> operator within a termary <code>if</code> statement.</li>
<li>Fixed some tests, and failing tests now result in a nonzero exit code.</li>
</ul>
</section>
<section id="1.12.5">
<h3><a href="https://github.com/jashkenas/coffeescript/compare/1.12.4...1.12.5">1.12.5</a>
<span class="timestamp"> &mdash; <time datetime="2017-04-10">2017-04-10</time></span>
</h3><ul>
<li>Better handling of <code>default</code>, <code>from</code>, <code>as</code> and <code>*</code> within <code>import</code> and <code>export</code> statements. You can now import or export a member named <code>default</code> and the compiler wont interpret it as the <code>default</code> keyword.</li>
<li>Fixed a bug where invalid octal escape sequences werent throwing errors in the compiler.</li>
</ul>
</section>
<section id="1.12.4">
<h3><a href="https://github.com/jashkenas/coffeescript/compare/1.12.3...1.12.4">1.12.4</a>
<span class="timestamp"> &mdash; <time datetime="2017-02-18">2017-02-18</time></span>
</h3><ul>
<li>The <code>cake</code> commands have been updated, with new <code>watch</code> options for most tasks. Clone the <a href="https://github.com/jashkenas/coffeescript">CoffeeScript repo</a> and run <code>cake</code> at the root of the repo to see the options.</li>
<li>Fixed a bug where <code>export</code>ing a referenced variable was preventing the variable from being declared.</li>
<li>Fixed a bug where the <code>coffee</code> command wasnt working for a <code>.litcoffee</code> file.</li>
<li>Bugfixes related to tokens and location data, for better source maps and improved compatibility with downstream tools.</li>
</ul>
</section>
<section id="1.12.3">
<h3><a href="https://github.com/jashkenas/coffeescript/compare/1.12.2...1.12.3">1.12.3</a>
<span class="timestamp"> &mdash; <time datetime="2017-01-24">2017-01-24</time></span>
</h3><ul>
<li><code>@</code> values can now be used as indices in <code>for</code> expressions. This loosens the compilation of <code>for</code> expressions to allow the index variable to be an <code>@</code> value, e.g. <code>do @visit for @node, @index in nodes</code>. Within <code>@visit</code>, the index of the current node (<code>@node</code>) would be available as <code>@index</code>.</li>
<li>CoffeeScripts patched <code>Error.prepareStackTrace</code> has been restored, with some revisions that should prevent the erroneous exceptions that were making life difficult for some downstream projects. This fixes the incorrect line numbers in stack traces since 1.12.2.</li>
<li>The <code>//=</code> operators output now wraps parentheses around the right operand, like the other assignment operators.</li>
</ul>
</section>
<section id="1.12.2">
<h3><a href="https://github.com/jashkenas/coffeescript/compare/1.12.1...1.12.2">1.12.2</a>
<span class="timestamp"> &mdash; <time datetime="2016-12-16">2016-12-16</time></span>
</h3><ul>
<li>The browser compiler can once again be built unminified via <code>MINIFY=false cake build:browser</code>.</li>
<li>The error-prone patched version of <code>Error.prepareStackTrace</code> has been removed.</li>
<li>Command completion in the REPL (pressing tab to get suggestions) has been fixed for Node 6.9.1+.</li>
<li>The <a href="/v2/test.html">browser-based tests</a> now include all the tests as the Node-based version.</li>
</ul>
</section>
<section id="1.12.1">
<h3><a href="https://github.com/jashkenas/coffeescript/compare/1.12.0...1.12.1">1.12.1</a>
<span class="timestamp"> &mdash; <time datetime="2016-12-07">2016-12-07</time></span>
</h3><ul>
<li>You can now import a module member named <code>default</code>, e.g. <code>import { default } from 'lib'</code>. Though like in ES2015, you cannot import an entire module and name it <code>default</code> (so <code>import default from 'lib'</code> is not allowed).</li>
<li>Fix regression where <code>from</code> as a variable name was breaking <code>for</code> loop declarations. For the record, <code>from</code> is not a reserved word in CoffeeScript; you may use it for variable names. <code>from</code> behaves like a keyword within the context of <code>import</code> and <code>export</code> statements, and in the declaration of a <code>for</code> loop; though you should also be able to use variables named <code>from</code> in those contexts, and the compiler should be able to tell the difference.</li>
</ul>
</section>
<section id="1.12.0">
<h3><a href="https://github.com/jashkenas/coffeescript/compare/1.11.1...1.12.0">1.12.0</a>
<span class="timestamp"> &mdash; <time datetime="2016-12-04">2016-12-04</time></span>
</h3><ul>
<li>CoffeeScript now supports ES2015 <a href="#tagged-template-literals">tagged template literals</a>. Note that using tagged template literals in your code makes you responsible for ensuring that either your runtime supports tagged template literals or that you transpile the output JavaScript further to a version your target runtime(s) support.</li>
<li>CoffeeScript now provides a <a href="#generator-iteration"><code>for…from</code></a> syntax for outputting ES2015 <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of"><code>for…of</code></a>. (Sorry they couldnt match, but we came up with <code>for…of</code> first for something else.) This allows iterating over generators or any other iterable object. Note that using <code>for…from</code> in your code makes you responsible for ensuring that either your runtime supports <code>for…of</code> or that you transpile the output JavaScript further to a version your target runtime(s) support.</li>
<li>Triple backticks (<code>```</code>) allow the creation of embedded JavaScript blocks where escaping single backticks is not required, which should improve interoperability with ES2015 template literals and with Markdown.</li>
<li>Within single-backtick embedded JavaScript, backticks can now be escaped via <code>\`</code>.</li>
<li>The browser tests now run in the browser again, and are accessible <a href="/v2/test.html">here</a> if you would like to test your browser.</li>
<li>CoffeeScript-only keywords in ES2015 <code>import</code>s and <code>export</code>s are now ignored.</li>
<li>The compiler now throws an error on trying to export an anonymous class.</li>
<li>Bugfixes related to tokens and location data, for better source maps and improved compatibility with downstream tools.</li>
</ul>
</section>
<section id="1.11.1">
<h3><a href="https://github.com/jashkenas/coffeescript/compare/1.11.0...1.11.1">1.11.1</a>
<span class="timestamp"> &mdash; <time datetime="2016-10-02">2016-10-02</time></span>
</h3><ul>
<li>Bugfix for shorthand object syntax after interpolated keys.</li>
<li>Bugfix for indentation-stripping in <code>&quot;&quot;&quot;</code> strings.</li>
<li>Bugfix for not being able to use the name “arguments” for a prototype property of class.</li>
<li>Correctly compile large hexadecimal numbers literals to <code>2e308</code> (just like all other large number literals do).</li>
</ul>
</section>
<section id="1.11.0">
<h3><a href="https://github.com/jashkenas/coffeescript/compare/1.10.0...1.11.0">1.11.0</a>
<span class="timestamp"> &mdash; <time datetime="2016-09-24">2016-09-24</time></span>
</h3><ul>
<li>CoffeeScript now supports ES2015 <a href="#modules"><code>import</code> and <code>export</code> syntax</a>.</li>
<li>Added the <code>-M, --inline-map</code> flag to the compiler, allowing you embed the source map directly into the output JavaScript, rather than as a separate file.</li>
<li>A bunch of fixes for <code>yield</code>:
<ul>
<li><code>yield return</code> can no longer mistakenly be used as an expression.</li>
<li><code>yield</code> now mirrors <code>return</code> in that it can be used stand-alone as well as with expressions. Where you previously wrote <code>yield undefined</code>, you may now write simply <code>yield</code>. However, this means also inheriting the same syntax limitations that <code>return</code> has, so these examples no longer compile:<blockquote class="uneditable-code-block"><pre><code>doubles = -&gt;
yield for i in [1..3]
i * 2
six = -&gt;
yield
2 * 3
</code></pre>
</blockquote></li>
<li>The JavaScript output is a bit nicer, with unnecessary parentheses and spaces, double indentation and double semicolons around <code>yield</code> no longer present.</li>
</ul>
</li>
<li><code>&amp;&amp;=</code>, <code>||=</code>, <code>and=</code> and <code>or=</code> no longer accidentally allow a space before the equals sign.</li>
<li>Improved several error messages.</li>
<li>Just like <code>undefined</code> compiles to <code>void 0</code>, <code>NaN</code> now compiles into <code>0/0</code> and <code>Infinity</code> into <code>2e308</code>.</li>
<li>Bugfix for renamed destructured parameters with defaults. <code>({a: b = 1}) -&gt;</code> no longer crashes the compiler.</li>
<li>Improved the internal representation of a CoffeeScript program. This is only noticeable to tools that use <code>CoffeeScript.tokens</code> or <code>CoffeeScript.nodes</code>. Such tools need to update to take account for changed or added tokens and nodes.</li>
<li>Several minor bug fixes, including:
<ul>
<li>The caught error in <code>catch</code> blocks is no longer declared unnecessarily, and no longer mistakenly named <code>undefined</code> for <code>catch</code>-less <code>try</code> blocks.</li>
<li>Unassignable parameter destructuring no longer crashes the compiler.</li>
<li>Source maps are now used correctly for errors thrown from .coffee.md files.</li>
<li><code>coffee -e 'throw null'</code> no longer crashes.</li>
<li>The REPL no longer crashes when using <code>.exit</code> to exit it.</li>
<li>Invalid JavaScript is no longer output when lots of <code>for</code> loops are used in the same scope.</li>
<li>A unicode issue when using stdin with the CLI.</li>
</ul>
</li>
</ul>
</section>
<section id="1.10.0">
<h3><a href="https://github.com/jashkenas/coffeescript/compare/1.9.3...1.10.0">1.10.0</a>
<span class="timestamp"> &mdash; <time datetime="2015-09-03">2015-09-03</time></span>
</h3><ul>
<li>CoffeeScript now supports ES2015-style destructuring defaults.</li>
<li><code>(offsetHeight: height) -&gt;</code> no longer compiles. That syntax was accidental and partly broken. Use <code>({offsetHeight: height}) -&gt;</code> instead. Object destructuring always requires braces.</li>
<li>Several minor bug fixes, including:
<ul>
<li>A bug where the REPL would sometimes report valid code as invalid, based on what you had typed earlier.</li>
<li>A problem with multiple JS contexts in the jest test framework.</li>
<li>An error in io.js where strict mode is set on internal modules.</li>
<li>A variable name clash for the caught error in <code>catch</code> blocks.</li>
</ul>
</li>
</ul>
</section>
<section id="1.9.3">
<h3><a href="https://github.com/jashkenas/coffeescript/compare/1.9.2...1.9.3">1.9.3</a>
<span class="timestamp"> &mdash; <time datetime="2015-05-27">2015-05-27</time></span>
</h3><ul>
<li>Bugfix for interpolation in the first key of an object literal in an implicit call.</li>
<li>Fixed broken error messages in the REPL, as well as a few minor bugs with the REPL.</li>
<li>Fixed source mappings for tokens at the beginning of lines when compiling with the <code>--bare</code> option. This has the nice side effect of generating smaller source maps.</li>
<li>Slight formatting improvement of compiled block comments.</li>
<li>Better error messages for <code>on</code>, <code>off</code>, <code>yes</code> and <code>no</code>.</li>
</ul>
</section>
<section id="1.9.2">
<h3><a href="https://github.com/jashkenas/coffeescript/compare/1.9.1...1.9.2">1.9.2</a>
<span class="timestamp"> &mdash; <time datetime="2015-04-15">2015-04-15</time></span>
</h3><ul>
<li>Fixed a <strong>watch</strong> mode error introduced in 1.9.1 when compiling multiple files with the same filename.</li>
<li>Bugfix for <code>yield</code> around expressions containing <code>this</code>.</li>
<li>Added a Ruby-style <code>-r</code> option to the REPL, which allows requiring a module before execution with <code>--eval</code> or <code>--interactive</code>.</li>
<li>In <code>&lt;script type=&quot;text/coffeescript&quot;&gt;</code> tags, to avoid possible duplicate browser requests for .coffee files, you can now use the <code>data-src</code> attribute instead of <code>src</code>.</li>
<li>Minor bug fixes for IE8, strict ES5 regular expressions and Browserify.</li>
</ul>
</section>
<section id="1.9.1">
<h3><a href="https://github.com/jashkenas/coffeescript/compare/1.9.0...1.9.1">1.9.1</a>
<span class="timestamp"> &mdash; <time datetime="2015-02-18">2015-02-18</time></span>
</h3><ul>
<li>Interpolation now works in object literal keys (again). You can use this to dynamically name properties.</li>
<li>Internal compiler variable names no longer start with underscores. This makes the generated JavaScript a bit prettier, and also fixes an issue with the completely broken and ungodly way that AngularJS “parses” function arguments.</li>
<li>Fixed a few <code>yield</code>-related edge cases with <code>yield return</code> and <code>yield throw</code>.</li>
<li>Minor bug fixes and various improvements to compiler error messages.</li>
</ul>
</section>
<section id="1.9.0">
<h3><a href="https://github.com/jashkenas/coffeescript/compare/1.8.0...1.9.0">1.9.0</a>
<span class="timestamp"> &mdash; <time datetime="2015-01-29">2015-01-29</time></span>
</h3><ul>
<li>CoffeeScript now supports ES2015 generators. A generator is simply a function that <code>yield</code>s.</li>
<li>More robust parsing and improved error messages for strings and regexes — especially with respect to interpolation.</li>
<li>Changed strategy for the generation of internal compiler variable names. Note that this means that <code>@example</code> function parameters are no longer available as naked <code>example</code> variables within the function body.</li>
<li>Fixed REPL compatibility with latest versions of Node and Io.js.</li>
<li>Various minor bug fixes.</li>
</ul>
</section>
<section id="1.8.0">
<h3><a href="https://github.com/jashkenas/coffeescript/compare/1.7.1...1.8.0">1.8.0</a>
<span class="timestamp"> &mdash; <time datetime="2014-08-26">2014-08-26</time></span>
</h3><ul>
<li>The <code>--join</code> option of the CLI is now deprecated.</li>
<li>Source maps now use <code>.js.map</code> as file extension, instead of just <code>.map</code>.</li>
<li>The CLI now exits with the exit code 1 when it fails to write a file to disk.</li>
<li>The compiler no longer crashes on unterminated, single-quoted strings.</li>
<li>Fixed location data for string interpolations, which made source maps out of sync.</li>
<li>The error marker in error messages is now correctly positioned if the code is indented with tabs.</li>
<li>Fixed a slight formatting error in CoffeeScripts source map-patched stack traces.</li>
<li>The <code>%%</code> operator now coerces its right operand only once.</li>
<li>It is now possible to require CoffeeScript files from Cakefiles without having to register the compiler first.</li>
<li>The CoffeeScript REPL is now exported and can be required using <code>require 'coffeescript/repl'</code>.</li>
<li>Fixes for the REPL in Node 0.11.</li>
</ul>
</section>
<section id="1.7.1">
<h3><a href="https://github.com/jashkenas/coffeescript/compare/1.7.0...1.7.1">1.7.1</a>
<span class="timestamp"> &mdash; <time datetime="2014-01-29">2014-01-29</time></span>
</h3><ul>
<li>Fixed a typo that broke node module lookup when running a script directly with the <code>coffee</code> binary.</li>
</ul>
</section>
<section id="1.7.0">
<h3><a href="https://github.com/jashkenas/coffeescript/compare/1.6.3...1.7.0">1.7.0</a>
<span class="timestamp"> &mdash; <time datetime="2014-01-28">2014-01-28</time></span>
</h3><ul>
<li>When requiring CoffeeScript files in Node you must now explicitly register the compiler. This can be done with <code>require 'coffeescript/register'</code> or <code>CoffeeScript.register()</code>. Also for configuration such as Mochas, use <strong>coffeescript/register</strong>.</li>
<li>Improved error messages, source maps and stack traces. Source maps now use the updated <code>//#</code> syntax.</li>
<li>Leading <code>.</code> now closes all open calls, allowing for simpler chaining syntax.</li>
<li>Added <code>**</code>, <code>//</code> and <code>%%</code> operators and <code>...</code> expansion in parameter lists and destructuring expressions.</li>
<li>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.</li>
<li>Closing brackets can now be indented and therefore no longer cause unexpected error.</li>
<li>Several breaking compilation fixes. Non-callable literals (strings, numbers etc.) dont 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.</li>
<li>Formatting of compiled block comments has been improved.</li>
<li>No more <code>-p</code> folders on Windows.</li>
<li>The <code>options</code> object passed to CoffeeScript is no longer mutated.</li>
</ul>
</section>
<section id="1.6.3">
<h3><a href="https://github.com/jashkenas/coffeescript/compare/1.6.2...1.6.3">1.6.3</a>
<span class="timestamp"> &mdash; <time datetime="2013-06-02">2013-06-02</time></span>
</h3><ul>
<li>The CoffeeScript REPL now remembers your history between sessions. Just like a proper REPL should.</li>
<li>You can now use <code>require</code> in Node to load <code>.coffee.md</code> Literate CoffeeScript files. In the browser, <code>text/literate-coffeescript</code> script tags.</li>
<li>The old <code>coffee --lint</code> command has been removed. It was useful while originally working on the compiler, but has been surpassed by JSHint. You may now use <code>-l</code> to pass literate files in over <strong>stdio</strong>.</li>
<li>Bugfixes for Windows path separators, <code>catch</code> without naming the error, and executable-class-bodies-with- prototypal-property-attachment.</li>
</ul>
</section>
<section id="1.6.2">
<h3><a href="https://github.com/jashkenas/coffeescript/compare/1.6.1...1.6.2">1.6.2</a>
<span class="timestamp"> &mdash; <time datetime="2013-03-18">2013-03-18</time></span>
</h3><ul>
<li>Source maps have been used to provide automatic line-mapping when running CoffeeScript directly via the <code>coffee</code> command, and for automatic line-mapping when running CoffeeScript directly in the browser. Also, to provide better error messages for semantic errors thrown by the compiler — <a href="http://cl.ly/NdOA">with colors, even</a>.</li>
<li>Improved support for mixed literate/vanilla-style CoffeeScript projects, and generating source maps for both at the same time.</li>
<li>Fixes for <strong>1.6.x</strong> regressions with overriding inherited bound functions, and for Windows file path management.</li>
<li>The <code>coffee</code> command can now correctly <code>fork()</code> both <code>.coffee</code> and <code>.js</code> files. (Requires Node.js 0.9+)</li>
</ul>
</section>
<section id="1.6.1">
<h3><a href="https://github.com/jashkenas/coffeescript/compare/1.5.0...1.6.1">1.6.1</a>
<span class="timestamp"> &mdash; <time datetime="2013-03-05">2013-03-05</time></span>
</h3><ul>
<li>First release of <a href="#source-maps">source maps</a>. Pass the <code>--map</code> flag to the compiler, and off you go. Direct all your thanks over to <a href="https://github.com/jwalton">Jason Walton</a>.</li>
<li>Fixed a 1.5.0 regression with multiple implicit calls against an indented implicit object. Combinations of implicit function calls and implicit objects should generally be parsed better now — but it still isnt good <em>style</em> to nest them too heavily.</li>
<li><code>.coffee.md</code> is now also supported as a Literate CoffeeScript file extension, for existing tooling. <code>.litcoffee</code> remains the canonical one.</li>
<li>Several minor fixes surrounding member properties, bound methods and <code>super</code> in class declarations.</li>
</ul>
</section>
<section id="1.5.0">
<h3><a href="https://github.com/jashkenas/coffeescript/compare/1.4.0...1.5.0">1.5.0</a>
<span class="timestamp"> &mdash; <time datetime="2013-02-25">2013-02-25</time></span>
</h3><ul>
<li>First release of <a href="#literate">Literate CoffeeScript</a>.</li>
<li>The CoffeeScript REPL is now based on the Node.js REPL, and should work better and more familiarly.</li>
<li>Returning explicit values from constructors is now forbidden. If you want to return an arbitrary value, use a function, not a constructor.</li>
<li>You can now loop over an array backwards, without having to manually deal with the indexes: <code>for item in list by -1</code></li>
<li>Source locations are now preserved in the CoffeeScript AST, although source maps are not yet being emitted.</li>
</ul>
</section>
<section id="1.4.0">
<h3><a href="https://github.com/jashkenas/coffeescript/compare/1.3.3...1.4.0">1.4.0</a>
<span class="timestamp"> &mdash; <time datetime="2012-10-23">2012-10-23</time></span>
</h3><ul>
<li>The CoffeeScript compiler now strips Microsofts UTF-8 BOM if it exists, allowing you to compile BOM-borked source files.</li>
<li>Fix Node/compiler deprecation warnings by removing <code>registerExtension</code>, and moving from <code>path.exists</code> to <code>fs.exists</code>.</li>
<li>Small tweaks to splat compilation, backticks, slicing, and the error for duplicate keys in object literals.</li>
</ul>
</section>
<section id="1.3.3">
<h3><a href="https://github.com/jashkenas/coffeescript/compare/1.3.1...1.3.3">1.3.3</a>
<span class="timestamp"> &mdash; <time datetime="2012-05-15">2012-05-15</time></span>
</h3><ul>
<li>Due to the new semantics of JavaScripts strict mode, CoffeeScript no longer guarantees that constructor functions have names in all runtimes. See <a href="https://github.com/jashkenas/coffeescript/issues/2052">#2052</a> for discussion.</li>
<li>Inside of a nested function inside of an instance method, its now possible to call <code>super</code> more reliably (walks recursively up).</li>
<li>Named loop variables no longer have different scoping heuristics than other local variables. (Reverts #643)</li>
<li>Fix for splats nested within the LHS of destructuring assignment.</li>
<li>Corrections to our compile time strict mode forbidding of octal literals.</li>
</ul>
</section>
<section id="1.3.1">
<h3><a href="https://github.com/jashkenas/coffeescript/compare/1.2.0...1.3.1">1.3.1</a>
<span class="timestamp"> &mdash; <time datetime="2012-04-10">2012-04-10</time></span>
</h3><ul>
<li>CoffeeScript now enforces all of JavaScripts <strong>Strict Mode</strong> early syntax errors at compile time. This includes old-style octal literals, duplicate property names in object literals, duplicate parameters in a function definition, deleting naked variables, setting the value of <code>eval</code> or <code>arguments</code>, and more. See a full discussion at <a href="https://github.com/jashkenas/coffeescript/issues/1547">#1547</a>.</li>
<li>The REPL now has a handy new multi-line mode for entering large blocks of code. Its useful when copy-and-pasting examples into the REPL. Enter multi-line mode with <code>Ctrl-V</code>. You may also now pipe input directly into the REPL.</li>
<li>CoffeeScript now prints a <code>Generated by CoffeeScript VERSION</code> header at the top of each compiled file.</li>
<li>Conditional assignment of previously undefined variables <code>a or= b</code> is now considered a syntax error.</li>
<li>A tweak to the semantics of <code>do</code>, which can now be used to more easily simulate a namespace: <code>do (x = 1, y = 2) -&gt;</code></li>
<li>Loop indices are now mutable within a loop iteration, and immutable between them.</li>
<li>Both endpoints of a slice are now allowed to be omitted for consistency, effectively creating a shallow copy of the list.</li>
<li>Additional tweaks and improvements to <code>coffee --watch</code> under Nodes “new” file watching API. Watch will now beep by default if you introduce a syntax error into a watched script. We also now ignore hidden directories by default when watching recursively.</li>
</ul>
</section>
<section id="1.2.0">
<h3><a href="https://github.com/jashkenas/coffeescript/compare/1.1.3...1.2.0">1.2.0</a>
<span class="timestamp"> &mdash; <time datetime="2011-12-18">2011-12-18</time></span>
</h3><ul>
<li>Multiple improvements to <code>coffee --watch</code> and <code>--join</code>. You may now use both together, as well as add and remove files and directories within a <code>--watch</code>d folder.</li>
<li>The <code>throw</code> statement can now be used as part of an expression.</li>
<li>Block comments at the top of the file will now appear outside of the safety closure wrapper.</li>
<li>Fixed a number of minor 1.1.3 regressions having to do with trailing operators and unfinished lines, and a more major 1.1.3 regression that caused bound functions <em>within</em> bound class functions to have the incorrect <code>this</code>.</li>
</ul>
</section>
<section id="1.1.3">
<h3><a href="https://github.com/jashkenas/coffeescript/compare/1.1.2...1.1.3">1.1.3</a>
<span class="timestamp"> &mdash; <time datetime="2011-11-08">2011-11-08</time></span>
</h3><ul>
<li>Ahh, whitespace. CoffeeScripts compiled JS now tries to space things out and keep it readable, as you can see in the examples on this page.</li>
<li>You can now call <code>super</code> in class level methods in class bodies, and bound class methods now preserve their correct context.</li>
<li>JavaScript has always supported octal numbers <code>010 is 8</code>, and hexadecimal numbers <code>0xf is 15</code>, but CoffeeScript now also supports binary numbers: <code>0b10 is 2</code>.</li>
<li>The CoffeeScript module has been nested under a subdirectory to make it easier to <code>require</code> individual components separately, without having to use <strong>npm</strong>. For example, after adding the CoffeeScript folder to your path: <code>require('coffeescript/lexer')</code></li>
<li>Theres a new “link” feature in Try CoffeeScript on this webpage. Use it to get a shareable permalink for your example script.</li>
<li>The <code>coffee --watch</code> feature now only works on Node.js 0.6.0 and higher, but now also works properly on Windows.</li>
<li>Lots of small bug fixes from <strong><a href="https://github.com/michaelficarra">@michaelficarra</a></strong>, <strong><a href="https://github.com/geraldalewis">@geraldalewis</a></strong>, <strong><a href="https://github.com/satyr">@satyr</a></strong>, and <strong><a href="https://github.com/trevorburnham">@trevorburnham</a></strong>.</li>
</ul>
</section>
<section id="1.1.2">
<h3><a href="https://github.com/jashkenas/coffeescript/compare/1.1.1...1.1.2">1.1.2</a>
<span class="timestamp"> &mdash; <time datetime="2011-08-04">2011-08-04</time></span>
</h3><p>Fixes for block comment formatting, <code>?=</code> compilation, implicit calls against control structures, implicit invocation of a try/catch block, variadic arguments leaking from local scope, line numbers in syntax errors following heregexes, property access on parenthesized number literals, bound class methods and super with reserved names, a REPL overhaul, consecutive compiled semicolons, block comments in implicitly called objects, and a Chrome bug.</p>
</section>
<section id="1.1.1">
<h3><a href="https://github.com/jashkenas/coffeescript/compare/1.1.0...1.1.1">1.1.1</a>
<span class="timestamp"> &mdash; <time datetime="2011-05-10">2011-05-10</time></span>
</h3><p>Bugfix release for classes with external constructor functions, see issue #1182.</p>
</section>
<section id="1.1.0">
<h3><a href="https://github.com/jashkenas/coffeescript/compare/1.0.1...1.1.0">1.1.0</a>
<span class="timestamp"> &mdash; <time datetime="2011-05-01">2011-05-01</time></span>
</h3><p>When running via the <code>coffee</code> executable, <code>process.argv</code> and friends now report <code>coffee</code> instead of <code>node</code>. Better compatibility with <strong>Node.js 0.4.x</strong> module lookup changes. The output in the REPL is now colorized, like Nodes is. Giving your concatenated CoffeeScripts a name when using <code>--join</code> is now mandatory. Fix for lexing compound division <code>/=</code> as a regex accidentally. All <code>text/coffeescript</code> tags should now execute in the order theyre included. Fixed an issue with extended subclasses using external constructor functions. Fixed an edge-case infinite loop in <code>addImplicitParentheses</code>. Fixed exponential slowdown with long chains of function calls. Globals no longer leak into the CoffeeScript REPL. Splatted parameters are declared local to the function.</p>
</section>
<section id="1.0.1">
<h3><a href="https://github.com/jashkenas/coffeescript/compare/1.0.0...1.0.1">1.0.1</a>
<span class="timestamp"> &mdash; <time datetime="2011-01-31">2011-01-31</time></span>
</h3><p>Fixed a lexer bug with Unicode identifiers. Updated REPL for compatibility with Node.js 0.3.7. Fixed requiring relative paths in the REPL. Trailing <code>return</code> and <code>return undefined</code> are now optimized away. Stopped requiring the core Node.js <code>util</code> module for back-compatibility with Node.js 0.2.5. Fixed a case where a conditional <code>return</code> would cause fallthrough in a <code>switch</code> statement. Optimized empty objects in destructuring assignment.</p>
</section>
<section id="1.0.0">
<h3><a href="https://github.com/jashkenas/coffeescript/compare/0.9.6...1.0.0">1.0.0</a>
<span class="timestamp"> &mdash; <time datetime="2010-12-24">2010-12-24</time></span>
</h3><p>CoffeeScript loops no longer try to preserve block scope when functions are being generated within the loop body. Instead, you can use the <code>do</code> keyword to create a convenient closure wrapper. Added a <code>--nodejs</code> flag for passing through options directly to the <code>node</code> executable. Better behavior around the use of pure statements within expressions. Fixed inclusive slicing through <code>-1</code>, for all browsers, and splicing with arbitrary expressions as endpoints.</p>
</section>
<section id="0.9.6">
<h3><a href="https://github.com/jashkenas/coffeescript/compare/0.9.5...0.9.6">0.9.6</a>
<span class="timestamp"> &mdash; <time datetime="2010-12-06">2010-12-06</time></span>
</h3><p>The REPL now properly formats stacktraces, and stays alive through asynchronous exceptions. Using <code>--watch</code> now prints timestamps as files are compiled. Fixed some accidentally-leaking variables within plucked closure-loops. Constructors now maintain their declaration location within a class body. Dynamic object keys were removed. Nested classes are now supported. Fixes execution context for naked splatted functions. Bugfix for inversion of chained comparisons. Chained class instantiation now works properly with splats.</p>
</section>
<section id="0.9.5">
<h3><a href="https://github.com/jashkenas/coffeescript/compare/0.9.4...0.9.5">0.9.5</a>
<span class="timestamp"> &mdash; <time datetime="2010-11-21">2010-11-21</time></span>
</h3><p>0.9.5 should be considered the first release candidate for CoffeeScript 1.0. There have been a large number of internal changes since the previous release, many contributed from <strong>satyr</strong>s <a href="https://github.com/satyr/coco">Coco</a> dialect of CoffeeScript. Heregexes (extended regexes) were added. Functions can now have default arguments. Class bodies are now executable code. Improved syntax errors for invalid CoffeeScript. <code>undefined</code> now works like <code>null</code>, and cannot be assigned a new value. There was a precedence change with respect to single-line comprehensions: <code>result = i for i in list</code>
used to parse as <code>result = (i for i in list)</code> by default … it now parses as
<code>(result = i) for i in list</code>.</p>
</section>
<section id="0.9.4">
<h3><a href="https://github.com/jashkenas/coffeescript/compare/0.9.3...0.9.4">0.9.4</a>
<span class="timestamp"> &mdash; <time datetime="2010-09-21">2010-09-21</time></span>
</h3><p>CoffeeScript now uses appropriately-named temporary variables, and recycles their references after use. Added <code>require.extensions</code> support for <strong>Node.js 0.3</strong>. Loading CoffeeScript in the browser now adds just a single <code>CoffeeScript</code> object to global scope. Fixes for implicit object and block comment edge cases.</p>
</section>
<section id="0.9.3">
<h3><a href="https://github.com/jashkenas/coffeescript/compare/0.9.2...0.9.3">0.9.3</a>
<span class="timestamp"> &mdash; <time datetime="2010-09-16">2010-09-16</time></span>
</h3><p>CoffeeScript <code>switch</code> statements now compile into JS <code>switch</code> statements — they previously compiled into <code>if/else</code> chains for JavaScript 1.3 compatibility. Soaking a function invocation is now supported. Users of the RubyMine editor should now be able to use <code>--watch</code> mode.</p>
</section>
<section id="0.9.2">
<h3><a href="https://github.com/jashkenas/coffeescript/compare/0.9.1...0.9.2">0.9.2</a>
<span class="timestamp"> &mdash; <time datetime="2010-08-23">2010-08-23</time></span>
</h3><p>Specifying the start and end of a range literal is now optional, eg. <code>array[3..]</code>. You can now say <code>a not instanceof b</code>. Fixed important bugs with nested significant and non-significant indentation (Issue #637). Added a <code>--require</code> flag that allows you to hook into the <code>coffee</code> command. Added a custom <code>jsl.conf</code> file for our preferred JavaScriptLint setup. Sped up Jison grammar compilation time by flattening rules for operations. Block comments can now be used with JavaScript-minifier-friendly syntax. Added JavaScripts compound assignment bitwise operators. Bugfixes to implicit object literals with leading number and string keys, as the subject of implicit calls, and as part of compound assignment.</p>
</section>
<section id="0.9.1">
<h3><a href="https://github.com/jashkenas/coffeescript/compare/0.9.0...0.9.1">0.9.1</a>
<span class="timestamp"> &mdash; <time datetime="2010-08-11">2010-08-11</time></span>
</h3><p>Bugfix release for <strong>0.9.1</strong>. Greatly improves the handling of mixed implicit objects, implicit function calls, and implicit indentation. String and regex interpolation is now strictly <code>#{ … }</code> (Ruby style). The compiler now takes a <code>--require</code> flag, which specifies scripts to run before compilation.</p>
</section>
<section id="0.9.0">
<h3><a href="https://github.com/jashkenas/coffeescript/compare/0.7.2...0.9.0">0.9.0</a>
<span class="timestamp"> &mdash; <time datetime="2010-08-04">2010-08-04</time></span>
</h3><p>The CoffeeScript <strong>0.9</strong> series is considered to be a release candidate for <strong>1.0</strong>; lets give her a shakedown cruise. <strong>0.9.0</strong> introduces a massive backwards-incompatible change: Assignment now uses <code>=</code>, and object literals use <code>:</code>, as in JavaScript. This allows us to have implicit object literals, and YAML-style object definitions. Half assignments are removed, in favor of <code>+=</code>, <code>or=</code>, and friends. Interpolation now uses a hash mark <code>#</code> instead of the dollar sign <code>$</code> — because dollar signs may be part of a valid JS identifier. Downwards range comprehensions are now safe again, and are optimized to straight for loops when created with integer endpoints. A fast, unguarded form of object comprehension was added: <code>for all key, value of object</code>. Mentioning the <code>super</code> keyword with no arguments now forwards all arguments passed to the function, as in Ruby. If you extend class <code>B</code> from parent class <code>A</code>, if <code>A</code> has an <code>extended</code> method defined, it will be called, passing in <code>B</code> — this enables static inheritance, among other things. Cleaner output for functions bound with the fat arrow. <code>@variables</code> can now be used in parameter lists, with the parameter being automatically set as a property on the object — useful in constructors and setter functions. Constructor functions can now take splats.</p>
</section>
<section id="0.7.2">
<h3><a href="https://github.com/jashkenas/coffeescript/compare/0.7.1...0.7.2">0.7.2</a>
<span class="timestamp"> &mdash; <time datetime="2010-07-12">2010-07-12</time></span>
</h3><p>Quick bugfix (right after 0.7.1) for a problem that prevented <code>coffee</code> command-line options from being parsed in some circumstances.</p>
</section>
<section id="0.7.1">
<h3><a href="https://github.com/jashkenas/coffeescript/compare/0.7.0...0.7.1">0.7.1</a>
<span class="timestamp"> &mdash; <time datetime="2010-07-11">2010-07-11</time></span>
</h3><p>Block-style comments are now passed through and printed as JavaScript block comments making them useful for licenses and copyright headers. Better support for running coffee scripts standalone via hashbangs. Improved syntax errors for tokens that are not in the grammar.</p>
</section>
<section id="0.7.0">
<h3><a href="https://github.com/jashkenas/coffeescript/compare/0.6.2...0.7.0">0.7.0</a>
<span class="timestamp"> &mdash; <time datetime="2010-06-28">2010-06-28</time></span>
</h3><p>Official CoffeeScript variable style is now camelCase, as in JavaScript. Reserved words are now allowed as object keys, and will be quoted for you. Range comprehensions now generate cleaner code, but you have to specify <code>by -1</code> if youd like to iterate downward. Reporting of syntax errors is greatly improved from the previous release. Running <code>coffee</code> with no arguments now launches the REPL, with Readline support. The <code>&lt;-</code> bind operator has been removed from CoffeeScript. The <code>loop</code> keyword was added, which is equivalent to a <code>while true</code> loop. Comprehensions that contain closures will now close over their variables, like the semantics of a <code>forEach</code>. You can now use bound function in class definitions (bound to the instance). For consistency, <code>a in b</code> is now an array presence check, and <code>a of b</code> is an object-key check. Comments are no longer passed through to the generated JavaScript.</p>
</section>
<section id="0.6.2">
<h3><a href="https://github.com/jashkenas/coffeescript/compare/0.6.1...0.6.2">0.6.2</a>
<span class="timestamp"> &mdash; <time datetime="2010-05-15">2010-05-15</time></span>
</h3><p>The <code>coffee</code> command will now preserve directory structure when compiling a directory full of scripts. Fixed two omissions that were preventing the CoffeeScript compiler from running live within Internet Explorer. Theres now a syntax for block comments, similar in spirit to CoffeeScripts heredocs. ECMA Harmony DRY-style pattern matching is now supported, where the name of the property is the same as the name of the value: <code>{name, length}: func</code>. Pattern matching is now allowed within comprehension variables. <code>unless</code> is now allowed in block form. <code>until</code> loops were added, as the inverse of <code>while</code> loops. <code>switch</code> statements are now allowed without switch object clauses. Compatible with Node.js <strong>v0.1.95</strong>.</p>
</section>
<section id="0.6.1">
<h3><a href="https://github.com/jashkenas/coffeescript/compare/0.6.0...0.6.1">0.6.1</a>
<span class="timestamp"> &mdash; <time datetime="2010-04-12">2010-04-12</time></span>
</h3><p>Upgraded CoffeeScript for compatibility with the new Node.js <strong>v0.1.90</strong> series.</p>
</section>
<section id="0.6.0">
<h3><a href="https://github.com/jashkenas/coffeescript/compare/0.5.6...0.6.0">0.6.0</a>
<span class="timestamp"> &mdash; <time datetime="2010-04-03">2010-04-03</time></span>
</h3><p>Trailing commas are now allowed, a-la Python. Static properties may be assigned directly within class definitions, using <code>@property</code> notation.</p>
</section>
<section id="0.5.6">
<h3><a href="https://github.com/jashkenas/coffeescript/compare/0.5.5...0.5.6">0.5.6</a>
<span class="timestamp"> &mdash; <time datetime="2010-03-23">2010-03-23</time></span>
</h3><p>Interpolation can now be used within regular expressions and heredocs, as well as strings. Added the <code>&lt;-</code> bind operator. Allowing assignment to half-expressions instead of special <code>||=</code>-style operators. The arguments object is no longer automatically converted into an array. After requiring <code>coffeescript</code>, Node.js can now directly load <code>.coffee</code> files, thanks to <strong>registerExtension</strong>. Multiple splats can now be used in function calls, arrays, and pattern matching.</p>
</section>
<section id="0.5.5">
<h3><a href="https://github.com/jashkenas/coffeescript/compare/0.5.4...0.5.5">0.5.5</a>
<span class="timestamp"> &mdash; <time datetime="2010-03-08">2010-03-08</time></span>
</h3><p>String interpolation, contributed by <a href="https://github.com/StanAngeloff">Stan Angeloff</a>. Since <code>--run</code> has been the default since <strong>0.5.3</strong>, updating <code>--stdio</code> and <code>--eval</code> to run by default, pass <code>--compile</code> as well if youd like to print the result.</p>
</section>
<section id="0.5.4">
<h3><a href="https://github.com/jashkenas/coffeescript/compare/0.5.3...0.5.4">0.5.4</a>
<span class="timestamp"> &mdash; <time datetime="2010-03-03">2010-03-03</time></span>
</h3><p>Bugfix that corrects the Node.js global constants <code>__filename</code> and <code>__dirname</code>. Tweaks for more flexible parsing of nested function literals and improperly-indented comments. Updates for the latest Node.js API.</p>
</section>
<section id="0.5.3">
<h3><a href="https://github.com/jashkenas/coffeescript/compare/0.5.2...0.5.3">0.5.3</a>
<span class="timestamp"> &mdash; <time datetime="2010-02-27">2010-02-27</time></span>
</h3><p>CoffeeScript now has a syntax for defining classes. Many of the core components (Nodes, Lexer, Rewriter, Scope, Optparse) are using them. Cakefiles can use <code>optparse.coffee</code> to define options for tasks. <code>--run</code> is now the default flag for the <code>coffee</code> command, use <code>--compile</code> to save JavaScripts. Bugfix for an ambiguity between RegExp literals and chained divisions.</p>
</section>
<section id="0.5.2">
<h3><a href="https://github.com/jashkenas/coffeescript/compare/0.5.1...0.5.2">0.5.2</a>
<span class="timestamp"> &mdash; <time datetime="2010-02-25">2010-02-25</time></span>
</h3><p>Added a compressed version of the compiler for inclusion in web pages as
<code>/v2/browser-compiler/coffeescript.js</code>. Itll automatically run any script tags with type <code>text/coffeescript</code> for you. Added a <code>--stdio</code> option to the <code>coffee</code> command, for piped-in compiles.</p>
</section>
<section id="0.5.1">
<h3><a href="https://github.com/jashkenas/coffeescript/compare/0.5.0...0.5.1">0.5.1</a>
<span class="timestamp"> &mdash; <time datetime="2010-02-24">2010-02-24</time></span>
</h3><p>Improvements to null soaking with the existential operator, including soaks on indexed properties. Added conditions to <code>while</code> loops, so you can use them as filters with <code>when</code>, in the same manner as comprehensions.</p>
</section>
<section id="0.5.0">
<h3><a href="https://github.com/jashkenas/coffeescript/compare/0.3.2...0.5.0">0.5.0</a>
<span class="timestamp"> &mdash; <time datetime="2010-02-21">2010-02-21</time></span>
</h3><p>CoffeeScript 0.5.0 is a major release, While there are no language changes, the Ruby compiler has been removed in favor of a self-hosting compiler written in pure CoffeeScript.</p>
</section>
<section id="0.3.2">
<h3><a href="https://github.com/jashkenas/coffeescript/compare/0.3.0...0.3.2">0.3.2</a>
<span class="timestamp"> &mdash; <time datetime="2010-02-08">2010-02-08</time></span>
</h3><p><code>@property</code> is now a shorthand for <code>this.property</code>.
Switched the default JavaScript engine from Narwhal to Node.js. Pass the <code>--narwhal</code> flag if youd like to continue using it.</p>
</section>
<section id="0.3.0">
<h3><a href="https://github.com/jashkenas/coffeescript/compare/0.2.6...0.3.0">0.3.0</a>
<span class="timestamp"> &mdash; <time datetime="2010-01-26">2010-01-26</time></span>
</h3><p>CoffeeScript 0.3 includes major syntax changes:
The function symbol was changed to <code>-&gt;</code>, and the bound function symbol is now <code>=&gt;</code>.
Parameter lists in function definitions must now be wrapped in parentheses.
Added property soaking, with the <code>?.</code> operator.
Made parentheses optional, when invoking functions with arguments.
Removed the obsolete block literal syntax.</p>
</section>
<section id="0.2.6">
<h3><a href="https://github.com/jashkenas/coffeescript/compare/0.2.5...0.2.6">0.2.6</a>
<span class="timestamp"> &mdash; <time datetime="2010-01-17">2010-01-17</time></span>
</h3><p>Added Python-style chained comparisons, the conditional existence operator <code>?=</code>, and some examples from <em>Beautiful Code</em>. Bugfixes relating to statement-to-expression conversion, arguments-to-array conversion, and the TextMate syntax highlighter.</p>
</section>
<section id="0.2.5">
<h3><a href="https://github.com/jashkenas/coffeescript/compare/0.2.4...0.2.5">0.2.5</a>
<span class="timestamp"> &mdash; <time datetime="2010-01-13">2010-01-13</time></span>
</h3><p>The conditions in switch statements can now take multiple values at once — If any of them are true, the case will run. Added the long arrow <code>==&gt;</code>, which defines and immediately binds a function to <code>this</code>. While loops can now be used as expressions, in the same way that comprehensions can. Splats can be used within pattern matches to soak up the rest of an array.</p>
</section>
<section id="0.2.4">
<h3><a href="https://github.com/jashkenas/coffeescript/compare/0.2.3...0.2.4">0.2.4</a>
<span class="timestamp"> &mdash; <time datetime="2010-01-12">2010-01-12</time></span>
</h3><p>Added ECMAScript Harmony style destructuring assignment, for dealing with extracting values from nested arrays and objects. Added indentation-sensitive heredocs for nicely formatted strings or chunks of code.</p>
</section>
<section id="0.2.3">
<h3><a href="https://github.com/jashkenas/coffeescript/compare/0.2.2...0.2.3">0.2.3</a>
<span class="timestamp"> &mdash; <time datetime="2010-01-11">2010-01-11</time></span>
</h3><p>Axed the unsatisfactory <code>ino</code> keyword, replacing it with <code>of</code> for object comprehensions. They now look like: <code>for prop, value of object</code>.</p>
</section>
<section id="0.2.2">
<h3><a href="https://github.com/jashkenas/coffeescript/compare/0.2.1...0.2.2">0.2.2</a>
<span class="timestamp"> &mdash; <time datetime="2010-01-10">2010-01-10</time></span>
</h3><p>When performing a comprehension over an object, use <code>ino</code>, instead of <code>in</code>, which helps us generate smaller, more efficient code at compile time.
Added <code>::</code> as a shorthand for saying <code>.prototype.</code>
The “splat” symbol has been changed from a prefix asterisk <code>*</code>, to a postfix ellipsis <code>...</code>
Added JavaScripts <code>in</code> operator, empty <code>return</code> statements, and empty <code>while</code> loops.
Constructor functions that start with capital letters now include a safety check to make sure that the new instance of the object is returned.
The <code>extends</code> keyword now functions identically to <code>goog.inherits</code> in Googles Closure Library.</p>
</section>
<section id="0.2.1">
<h3><a href="https://github.com/jashkenas/coffeescript/compare/0.2.0...0.2.1">0.2.1</a>
<span class="timestamp"> &mdash; <time datetime="2010-01-05">2010-01-05</time></span>
</h3><p>Arguments objects are now converted into real arrays when referenced.</p>
</section>
<section id="0.2.0">
<h3><a href="https://github.com/jashkenas/coffeescript/compare/0.1.6...0.2.0">0.2.0</a>
<span class="timestamp"> &mdash; <time datetime="2010-01-05">2010-01-05</time></span>
</h3><p>Major release. Significant whitespace. Better statement-to-expression conversion. Splats. Splice literals. Object comprehensions. Blocks. The existential operator. Many thanks to all the folks who posted issues, with special thanks to <a href="https://github.com/liamoc">Liam OConnor-Davis</a> for whitespace and expression help.</p>
</section>
<section id="0.1.6">
<h3><a href="https://github.com/jashkenas/coffeescript/compare/0.1.5...0.1.6">0.1.6</a>
<span class="timestamp"> &mdash; <time datetime="2009-12-27">2009-12-27</time></span>
</h3><p>Bugfix for running <code>coffee --interactive</code> and <code>--run</code> from outside of the CoffeeScript directory. Bugfix for nested function/if-statements.</p>
</section>
<section id="0.1.5">
<h3><a href="https://github.com/jashkenas/coffeescript/compare/0.1.4...0.1.5">0.1.5</a>
<span class="timestamp"> &mdash; <time datetime="2009-12-26">2009-12-26</time></span>
</h3><p>Array slice literals and array comprehensions can now both take Ruby-style ranges to specify the start and end. JavaScript variable declaration is now pushed up to the top of the scope, making all assignment statements into expressions. You can use <code>\</code> to escape newlines. The <code>coffeescript</code> command is now called <code>coffee</code>.</p>
</section>
<section id="0.1.4">
<h3><a href="https://github.com/jashkenas/coffeescript/compare/0.1.3...0.1.4">0.1.4</a>
<span class="timestamp"> &mdash; <time datetime="2009-12-25">2009-12-25</time></span>
</h3><p>The official CoffeeScript extension is now <code>.coffee</code> instead of <code>.cs</code>, which properly belongs to <a href="https://en.wikipedia.org/wiki/C_Sharp_(programming_language)">C#</a>. Due to popular demand, you can now also use <code>=</code> to assign. Unlike JavaScript, <code>=</code> can also be used within object literals, interchangeably with <code>:</code>. Made a grammatical fix for chained function calls like <code>func(1)(2)(3)(4)</code>. Inheritance and super no longer use <code>__proto__</code>, so they should be IE-compatible now.</p>
</section>
<section id="0.1.3">
<h3><a href="https://github.com/jashkenas/coffeescript/compare/0.1.2...0.1.3">0.1.3</a>
<span class="timestamp"> &mdash; <time datetime="2009-12-25">2009-12-25</time></span>
</h3><p>The <code>coffee</code> command now includes <code>--interactive</code>, which launches an interactive CoffeeScript session, and <code>--run</code>, which directly compiles and executes a script. Both options depend on a working installation of Narwhal. The <code>aint</code> keyword has been replaced by <code>isnt</code>, which goes together a little smoother with <code>is</code>. Quoted strings are now allowed as identifiers within object literals: eg. <code>{&quot;5+5&quot;: 10}</code>. All assignment operators now use a colon: <code>+:</code>, <code>-:</code>, <code>*:</code>, etc.</p>
</section>
<section id="0.1.2">
<h3><a href="https://github.com/jashkenas/coffeescript/compare/0.1.1...0.1.2">0.1.2</a>
<span class="timestamp"> &mdash; <time datetime="2009-12-24">2009-12-24</time></span>
</h3><p>Fixed a bug with calling <code>super()</code> through more than one level of inheritance, with the re-addition of the <code>extends</code> keyword. Added experimental <a href="http://narwhaljs.org/">Narwhal</a> support (as a Tusk package), contributed by <a href="http://blog.tlrobinson.net/">Tom Robinson</a>, including <strong>bin/cs</strong> as a CoffeeScript REPL and interpreter. New <code>--no-wrap</code> option to suppress the safety function wrapper.</p>
</section>
<section id="0.1.1">
<h3><a href="https://github.com/jashkenas/coffeescript/compare/0.1.0...0.1.1">0.1.1</a>
<span class="timestamp"> &mdash; <time datetime="2009-12-24">2009-12-24</time></span>
</h3><p>Added <code>instanceof</code> and <code>typeof</code> as operators.</p>
</section>
<section id="0.1.0">
<h3><a href="https://github.com/jashkenas/coffeescript/compare/8e9d637985d2dc9b44922076ad54ffef7fa8e9c2...0.1.0">0.1.0</a>
<span class="timestamp"> &mdash; <time datetime="2009-12-24">2009-12-24</time></span>
</h3><p>Initial CoffeeScript release.</p>
</section>
</section>
</main>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js" integrity="sha384-xBuQ/xzmlsLoJpyjoggmTEz8OWUFM0/RC5BsqQBDX2v5cMvDHcMakNTNrHIW2I5f" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js" integrity="sha384-uefMccjFJAIv6A+rW+L4AHf99KvxDjWSu1z9VI8SKNVmz4sk7buKt/6v9KI65qnm" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/combine/npm/codemirror@5.37.0/lib/codemirror.js,npm/codemirror@5.37.0/mode/coffeescript/coffeescript.js,npm/codemirror@5.37.0/addon/lint/coffeescript-lint.js,npm/codemirror@5.37.0/mode/javascript/javascript.js"></script>
<script src="browser-compiler/coffeescript.js"></script>
<script>
(function(){window.location.origin||(window.location.origin="".concat(window.location.protocol,"//").concat(window.location.hostname)),window.GA_TRACKING_ID="UA-106156830-1",null==window.dataLayer&&(window.dataLayer=[]),window.gtag=function(){window.dataLayer.push(arguments)},window.gtag("js",new Date),window.gtag("config",window.GA_TRACKING_ID),$(document).ready(function(){var clearHash,closeTry,editors,initializeEditor,initializeScrollspyFromHash,initializeTryEditors,lastCompilationElapsedTime,previousHash,replaceState,textareas,toggleSidebar,toggleTry;if($("time").each(function(index,el){var date,formattedDate;return date=el.dateTime||$(el).text(),formattedDate=new Date(date).toLocaleDateString(void 0,{year:"numeric",month:"long",day:"numeric"}),$(el).text(formattedDate.toString())}),toggleSidebar=function(){return $(".navbar-toggler, .sidebar").toggleClass("show")},$("[data-toggle=\"offcanvas\"]").click(toggleSidebar),$("[data-action=\"sidebar-nav\"]").click(function(event){return $(".navbar-toggler").is(":visible")&&(event.preventDefault(),toggleSidebar(),setTimeout(function(){return window.location=event.target.href},260)),gtag("event","sidebar_navigate",{event_category:"navigation",event_label:event.target.href.replace(window.location.origin,"")})}),$(".main").scrollspy({target:"#contents",offset:Math.round($("main").css("padding-top").replace("px",""))}),initializeScrollspyFromHash=function(hash){return $("#contents a.active[href!='".concat(hash,"']")).removeClass("show")},$(".main").on("activate.bs.scrollspy",function(event,target){var $target;if($("#contents a.active[href!='".concat(target.relatedTarget,"']")).removeClass("show"),$target=$("#contents a[href='".concat(target.relatedTarget,"']")),$target.prop("href")!=="".concat(window.location.origin,"/#try"))return replaceState($target.prop("href")),gtag("config",GA_TRACKING_ID,{page_path:$target.prop("href").replace(window.location.origin,"")})}),textareas=[],editors=[],lastCompilationElapsedTime=200,$("textarea").each(function(index){return textareas[index]=this,$(this).data("index",index)}),initializeEditor=function($textarea){var editor,index,mode,pending;if(index=$textarea.data("index"),mode=$textarea.hasClass("javascript-output")?"javascript":"coffeescript",editors[index]=editor=CodeMirror.fromTextArea($textarea[0],{mode:mode,theme:"twilight",indentUnit:2,tabSize:2,lineWrapping:!0,lineNumbers:!1,inputStyle:"contenteditable",readOnly:"coffeescript"!==mode,viewportMargin:2e308}),"coffeescript"===mode)return pending=null,editor.on("change",function(){return clearTimeout(pending),pending=setTimeout(function(){var coffee,exception,lastCompilationStartTime,link,output;lastCompilationStartTime=Date.now();try{if(coffee=editor.getValue(),0===index&&$("#try").hasClass("show")){$("#try").hasClass("show")&&(link="try:".concat(encodeURIComponent(coffee)),replaceState("".concat(window.location.href.split("#")[0],"#").concat(link)));try{null!=window.localStorage&&window.localStorage.setItem("tryCoffeeScriptCode",coffee)}catch(error){exception=error}}output=CoffeeScript.compile(coffee,{bare:!0}),lastCompilationElapsedTime=Math.max(200,Date.now()-lastCompilationStartTime)}catch(error){exception=error,output="".concat(exception)}return editors[index+1].setValue(output),gtag("event","edit_code",{event_category:"engagement",event_label:$textarea.closest("[data-example]").data("example")})},lastCompilationElapsedTime)}),editor.addKeyMap({Tab:function Tab(cm){return cm.somethingSelected()?cm.indentSelection("add"):/^\t/m.test(cm.getValue())?cm.execCommand("insertTab"):cm.execCommand("insertSoftTab")},"Shift-Tab":function ShiftTab(cm){return cm.indentSelection("subtract")},Enter:function Enter(cm){return cm.options.indentWithTabs=/^\t/m.test(cm.getValue()),cm.execCommand("newlineAndIndent")}})},$(".placeholder-code").one("mouseover",function(){var $siblingColumn,$textarea;return $textarea=$(this).prev("textarea"),$(this).remove(),initializeEditor($textarea),$siblingColumn=$($textarea.parent().siblings()[0]),$siblingColumn.children(".placeholder-code").remove(),initializeEditor($($siblingColumn.children("textarea")[0]))}),initializeTryEditors=function(){return initializeEditor($("#try-coffeescript-coffee")),initializeEditor($("#try-coffeescript-js"))},$("[data-action=\"run-code-example\"]").click(function(){var index,js,run;return run=$(this).data("run"),index=$("#".concat($(this).data("example"),"-js")).data("index"),js=null==editors[index]?$(textareas[index]).val():editors[index].getValue(),!0!==run&&(js="".concat(js,"\nalert(").concat(unescape(run),");")),window.eval(js),gtag("event","run_code",{event_category:"engagement",event_label:$(this).closest("[data-example]").data("example")})}),previousHash=null,toggleTry=function(checkLocalStorage){var coffee,exception;if($("#try, #try-link").toggleClass("show"),!$("#try").hasClass("show"))return previousHash?replaceState(previousHash):clearHash();if(window.location.hash&&(previousHash=window.location.hash),0===$("#try .CodeMirror").length&&initializeTryEditors(),checkLocalStorage&&null!=window.localStorage)try{return coffee=window.localStorage.getItem("tryCoffeeScriptCode"),null==coffee?replaceState("#try"):editors[0].setValue(coffee)}catch(error){return exception=error,replaceState("#try")}else return replaceState("#try")},closeTry=function(){return $("#try, #try-link").removeClass("show"),previousHash?replaceState(previousHash):clearHash()},$("[data-toggle=\"try\"]").click(function(event){return event.preventDefault(),toggleTry(!0)}),$("[data-close=\"try\"]").click(closeTry),$("[data-action=\"scroll-to-top\"]").click(function(){if(!$("#try").hasClass("show"))return $(".main")[0].scrollTop=0,setTimeout(clearHash,10)}),clearHash=function(){return window.history.replaceState({},document.title,window.location.pathname)},replaceState=function(newURL){return 0===(null==newURL?void 0:newURL.indexOf("#"))&&(newURL="".concat(window.location.pathname).concat(newURL)),window.history.replaceState({},document.title,newURL||"")},$(window).on("hashchange",function(){if(""===window.location.hash)return clearHash()}),null!=window.location.hash){if("#try"===window.location.hash)return toggleTry(!0);if(0===window.location.hash.indexOf("#try"))return 0===$("#try .CodeMirror").length&&initializeTryEditors(),editors[0].setValue(decodeURIComponent(window.location.hash.slice(5))),toggleTry(!1);if(""===window.location.hash)return clearHash();if(initializeScrollspyFromHash(window.location.hash),1<window.location.hash.length)return document.getElementById(window.location.hash.slice(1).replace(/try:.*/,"")).scrollIntoView()}})}).call(this);
</script>
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-106156830-1"></script>
</body>
</html>