The golden rule of CoffeeScript is: “It’s just JavaScript.” 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.

CoffeeScript is a little language that compiles into JavaScript. 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.

CoffeeScript on the topleft, compiled JavaScript output on the bottomright. The CoffeeScript is editable!

This list may be incomplete, and excludes versions of Node that support newer features behind flags; please refer to node.green for full details. You can run the tests in your browser to see what your browser supports. It is your responsibility to ensure that your runtime supports the modern features you use; or that you transpile your code. When in doubt, transpile.

Most modern JavaScript features that CoffeeScript supports can run natively in Node 7.6+, meaning that Node can run CoffeeScript’s output without any further processing required. Here are some notable exceptions:

There are very few breaking changes from CoffeeScript 1.x to 2 ; we hope the upgrade process is smooth for most projects.

The biggest change in CoffeeScript 2 is that now the CoffeeScript compiler produces modern JavaScript syntax (ES6, or ES2015 and later). A CoffeeScript => becomes a JS => , a CoffeeScript class becomes a JS class and so on. Major new features in CoffeeScript 2 include async functions and JSX . You can read more in the announcement .

If you plan to use the --transpile option (see Transpilation ) you will need to also install @babel/core either globally or locally, depending on whether you are running a globally or locally installed version of CoffeeScript.

The coffee and cake 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.

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 project’s dependencies. Within that project’s folder:

This will make the coffee and cake commands available globally.

To install, first make sure you have a working copy of the latest stable version of Node.js . You can then install CoffeeScript globally with npm :

The command-line version of coffee is available as a Node.js utility, requiring Node 6 or later. The core compiler however, does not depend on Node, and can be run in any JavaScript environment, or in the browser (see Try CoffeeScript ).

Note that transpiling doesn’t automatically supply polyfills for your code. CoffeeScript itself will output Array.indexOf if you use the in operator, or destructuring or spread/rest syntax; and Function.bind if you use a bound ( => ) 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. You’ll 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 @babel/polyfill , though there are many other strategies .

You can also transpile CoffeeScript’s output without using the transpile 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 Gulp , Webpack , Grunt and Broccoli .

If you’re using CoffeeScript via the Node API , where you call CoffeeScript.compile with a string to be compiled and an options object, the transpile key of the options object should be the Babel options:

Once you have @babel/core and @babel/preset-env (or other presets or plugins) installed, and a .babelrc file (or other equivalent) in place, you can use coffee --transpile to pipe CoffeeScript’s output through Babel using the options you’ve saved.

See Babel’s website to learn about presets and plugins and the multitude of options you have. Another preset you might need is @babel/plugin-transform-react-jsx if you’re using JSX with React (JSX can also be used with other frameworks).

By default, Babel doesn’t do anything—it doesn’t 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 .babelrc file in the folder containing the files you’re compiling, or in any parent folder up the path above those files. (Babel supports other ways , too.) A minimal .babelrc file would be just { "presets": ["@babel/env"] } . This implies that you have installed @babel/preset-env :

Or if you’re running the coffee command outside of a project folder, using a globally-installed coffeescript module, @babel/core needs to be installed globally:

To make things easy, CoffeeScript has built-in support for the popular Babel transpiler. You can use it via the --transpile command-line option or the transpile Node API option. To use either, @babel/core must be installed in your project:

CoffeeScript 2 generates JavaScript that uses the latest, modern syntax. The runtime or browsers where you want your code to run might not support all of that syntax . 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, { a } = obj into a = obj.a . This is done via transpilers like Babel , Bublé or Traceur Compiler .

The compile method has the signature compile(code, options) where code is a string of CoffeeScript code, and the optional options is an object with some or all of the following properties:

'console.log "Mmmmm, I could really go for some #{Math.pi}"'

If you want to use the compiler’s API, for example to make an app that compiles strings of CoffeeScript on the fly, you can require the full module:

If you’d like to use Node.js’ CommonJS to require CoffeeScript files, e.g. require './app.coffee' , you must first “register” CoffeeScript as an extension:

Once installed, you should have access to the coffee command, which can execute scripts, compile .coffee files into .js , and provide an interactive REPL. The coffee command takes the following options:

Language Reference

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.

Many of the examples can be run (where it makes sense) by pressing the ▶ button on the right. The CoffeeScript on the left is editable, and the JavaScript will update as you edit.

First, the basics: CoffeeScript uses significant whitespace to delimit blocks of code. You don’t need to use semicolons ; 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 { } to surround blocks of code in functions, if-statements, switch, and try/catch, use indentation.

You don’t need to use parentheses to invoke a function if you’re passing arguments. The implicit call wraps forward to the end of the line or block expression.

console.log sys.inspect object → console.log(sys.inspect(object));

Functions Functions are defined by an optional list of parameters in parentheses, an arrow, and the function body. The empty function looks like this: -> square = (x) -> x * x cube = (x) -> square(x) * x square = ( x ) -> x * x cube = ( x ) -> square ( x ) * x var cube, square; square = function(x) { return x * x; }; cube = function(x) { return square(x) * x; }; var cube , square ; square = function ( x ) { return x * x ; }; cube = function ( x ) { return square ( x ) * x ; }; cube(5) Functions may also have default values for arguments, which will be used if the incoming argument is missing ( undefined ). fill = (container, liquid = "coffee") -> "Filling the #{container} with #{liquid}..." fill = ( container , liquid = "coffee" ) -> "Filling the #{container} with #{liquid}..." var fill; fill = function(container, liquid = "coffee") { return `Filling the ${container} with ${liquid}...`; }; var fill ; fill = function ( container , liquid = "coffee" ) { return `Filling the ${ container } with ${ liquid }...` ; }; fill("cup")

Strings Like JavaScript and many other languages, CoffeeScript supports strings as delimited by the " or ' characters. CoffeeScript also supports string interpolation within " -quoted strings, using #{ … } . Single-quoted strings are literal. You may even use interpolation in object keys. author = "Wittgenstein" quote = "A picture is a fact. -- #{ author }" sentence = "#{ 22 / 7 } is a decent approximation of π" author = "Wittgenstein" quote = "A picture is a fact. -- #{ author }" sentence = "#{ 22 / 7 } is a decent approximation of π" var author, quote, sentence; author = "Wittgenstein"; quote = `A picture is a fact. -- ${author}`; sentence = `${22 / 7} is a decent approximation of π`; var author , quote , sentence ; author = "Wittgenstein" ; quote = `A picture is a fact. -- ${ author }` ; sentence = `${ 22 / 7 } is a decent approximation of π` ; sentence Multiline strings are allowed in CoffeeScript. Lines are joined by a single space unless they end with a backslash. Indentation is ignored. 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..." 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..." 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..."; 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..." ; mobyDick Block strings, delimited by """ or ''' , can be used to hold formatted or indentation-sensitive text (or, if you just don’t 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. html = """ cup of coffeescript """ html = """ <strong> cup of coffeescript </strong> """ var html; html = ` cup of coffeescript `; var html ; html = `<strong> cup of coffeescript </strong>` ; html Double-quoted block strings, like other double-quoted strings, allow interpolation.

Objects and Arrays 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 YAML. 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 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 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 } }; 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 } }; song.join(" … ") CoffeeScript has a shortcut for creating objects when you want the key to be set with a variable of the same name. Note that the { and } are required for this shorthand. name = "Michelangelo" mask = "orange" weapon = "nunchuks" turtle = {name, mask, weapon} output = "#{turtle.name} wears an #{turtle.mask} mask. Watch out for his #{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}!" 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}!`; 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 }!` ;

Lexical Scoping and Variable Safety The CoffeeScript compiler takes care to make sure that all of your variables are properly declared within lexical scope — you never need to write var yourself. outer = 1 changeNumbers = -> inner = -1 outer = 10 inner = changeNumbers() outer = 1 changeNumbers = -> inner = -1 outer = 10 inner = changeNumbers () var changeNumbers, inner, outer; outer = 1; changeNumbers = function() { var inner; inner = -1; return outer = 10; }; inner = changeNumbers(); var changeNumbers , inner , outer ; outer = 1 ; changeNumbers = function () { var inner ; inner = - 1 ; return outer = 10 ; }; inner = changeNumbers (); inner Notice how all of the variable declarations have been pushed up to the top of the closest scope, the first time they appear. outer is not redeclared within the inner function, because it’s already in scope; inner 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. Because you don’t have direct access to the var keyword, it’s impossible to shadow an outer variable on purpose, you may only refer to it. So be careful that you’re not reusing the name of an external variable accidentally, if you’re writing a deeply nested function. Although suppressed within this documentation for clarity, all CoffeeScript output (except in files with import or export statements) is wrapped in an anonymous function: (function(){ … })(); . This safety wrapper, combined with the automatic generation of the var keyword, make it exceedingly difficult to pollute the global namespace by accident. (The safety wrapper can be disabled with the bare option, and is unnecessary and automatically disabled when using modules.) If you’d like to create top-level variables for other scripts to use, attach them as properties on window ; attach them as properties on the exports object in CommonJS; or use an export statement. If you’re targeting both CommonJS and the browser, the existential operator (covered below), gives you a reliable way to figure out where to add them: exports ? this . Since CoffeeScript takes care of all variable declaration, it is not possible to declare variables with ES2015’s let or const . This is intentional; 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.

If, Else, Unless, and Conditional Assignment if / else statements can be written without the use of parentheses and curly brackets. As with functions and other block expressions, multi-line conditionals are delimited by indentation. There’s also a handy postfix form, with the if or unless at the end. CoffeeScript can compile if 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 if statement on a single line. mood = greatlyImproved if singing if happy and knowsIt clapsHands() chaChaCha() else showIt() date = if friday then sue else jill mood = greatlyImproved if singing if happy and knowsIt clapsHands () chaChaCha () else showIt () date = if friday then sue else jill var date, mood; if (singing) { mood = greatlyImproved; } if (happy && knowsIt) { clapsHands(); chaChaCha(); } else { showIt(); } date = friday ? sue : jill; var date , mood ; if ( singing ) { mood = greatlyImproved ; } if ( happy && knowsIt ) { clapsHands (); chaChaCha (); } else { showIt (); } date = friday ? sue : jill ;

Splats, or Rest Parameters/Spread Syntax The JavaScript arguments object is a useful way to work with functions that accept variable numbers of arguments. CoffeeScript provides splats ... , both for function definition as well as invocation, making variable numbers of arguments a little bit more palatable. ES2015 adopted this feature as their rest parameters. 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 ', '} """ 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 ', '} """ 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} Silver: ${silver} The Field: ${rest.join(', ')}`); 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 } Silver: ${ silver } The Field: ${ rest . join ( ', ' ) }` ); Splats also let us elide array elements… popular = ['pepperoni', 'sausage', 'cheese'] unwanted = ['anchovies', 'olives'] all = [popular..., unwanted..., 'mushrooms'] popular = [ 'pepperoni' , 'sausage' , 'cheese' ] unwanted = [ 'anchovies' , 'olives' ] all = [ popular ..., unwanted ..., 'mushrooms' ] var all, popular, unwanted; popular = ['pepperoni', 'sausage', 'cheese']; unwanted = ['anchovies', 'olives']; all = [...popular, ...unwanted, 'mushrooms']; var all , popular , unwanted ; popular = [ 'pepperoni' , 'sausage' , 'cheese' ]; unwanted = [ 'anchovies' , 'olives' ]; all = [ popular , unwanted , 'mushrooms' ]; all …and object properties. user = name: 'Werner Heisenberg' occupation: 'theoretical physicist' currentUser = { user..., status: 'Uncertain' } user = name : 'Werner Heisenberg' occupation : 'theoretical physicist' currentUser = { user ..., status : 'Uncertain' } var currentUser, user; user = { name: 'Werner Heisenberg', occupation: 'theoretical physicist' }; currentUser = { ...user, status: 'Uncertain' }; var currentUser , user ; user = { name : 'Werner Heisenberg' , occupation : 'theoretical physicist' }; currentUser = { user , status : 'Uncertain' }; JSON.stringify(currentUser) In ECMAScript this is called spread syntax, and has been supported for arrays since ES2015 and objects since ES2018.

Loops and Comprehensions Most of the loops you’ll write in CoffeeScript will be comprehensions over arrays, objects, and ranges. Comprehensions replace (and compile into) for 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. # 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' eat = ( food ) -> "#{food} eaten." eat food for food in [ 'toast' , 'cheese' , 'wine' ] courses = [ 'greens' , 'caviar' , 'truffles' , 'roast' , 'cake' ] menu = ( i , dish ) -> "Menu Item #{i}: #{dish}" menu i + 1 , dish for dish , i in courses foods = [ 'broccoli' , 'spinach' , 'chocolate' ] eat food for food in foods when food isnt 'chocolate' // 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); } } 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 ); } 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 ); } foods = [ 'broccoli' , 'spinach' , 'chocolate' ]; for ( l = 0 , len2 = foods . length ; l < len2 ; l ++ ) { food = foods [ l ]; if ( food !== 'chocolate' ) { eat ( food ); } } Comprehensions should be able to handle most places where you otherwise would use a loop, each / forEach , map , or select / filter , for example:

shortNames = (name for name in list when name.length < 5)

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. countdown = (num for num in [10..1]) countdown = ( num for num in [ 10..1 ]) var countdown, num; countdown = (function() { var i, results; results = []; for (num = i = 10; i >= 1; num = --i) { results.push(num); } return results; })(); var countdown , num ; countdown = ( function () { var i , results ; results = []; for ( num = i = 10 ; i >= 1 ; num = -- i ) { results . push ( num ); } return results ; })(); countdown 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 you’re not accidentally returning the results of the comprehension in these cases, by adding a meaningful return value — like true — or null , to the bottom of your function. To step through a range comprehension in fixed-size chunks, use by , for example: evens = (x for x in [0..10] by 2) If you don’t need the current iteration value you may omit it: browser.closeCurrentTab() for [0...count] Comprehensions can also be used to iterate over the keys and values in an object. Use of to signal comprehension over the properties of an object instead of the values in an array. yearsOld = max: 10, ida: 9, tim: 11 ages = for child, age of yearsOld "#{child} is #{age}" yearsOld = max : 10 , ida : 9 , tim : 11 ages = for child , age of yearsOld "#{child} is #{age}" 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; })(); 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 ; })(); ages.join(", ") If you would like to iterate over just the keys that are defined on the object itself, by adding a hasOwnProperty check to avoid properties that may be inherited from the prototype, use for own key, value of object . To iterate a generator function, use from . See Generator Functions. The only low-level loop that CoffeeScript provides is the while loop. The main difference from JavaScript is that the while loop can be used as an expression, returning an array containing the result of each iteration through the loop. # 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." if this . studyingEconomics buy () while supply > demand sell () until supply > demand num = 6 lyrics = while num -= 1 "#{num} little monkeys, jumping on the bed. One fell out and bumped his head." // 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; })(); var lyrics , num ; if ( this . studyingEconomics ) { while ( supply > demand ) { buy (); } while ( ! ( supply > demand )) { sell (); } } 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 ; })(); lyrics.join("

") For readability, the until keyword is equivalent to while not , and the loop keyword is equivalent to while true . When using a JavaScript loop to generate functions, it’s common to insert a closure wrapper in order to ensure that loop variables are closed over, and all the generated functions don’t just share the final values. CoffeeScript provides the do keyword, which immediately invokes a passed function, forwarding any arguments. 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() 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 () 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); } 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 ); }

Array Slicing and Splicing with Ranges Ranges can also be used to extract slices of arrays. With two dots ( 3..6 ), the range is inclusive ( 3, 4, 5, 6 ); with three dots ( 3...6 ), the range excludes the end ( 3, 4, 5 ). Slices indices have useful defaults. An omitted first index defaults to zero and an omitted second index defaults to the size of the array. numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9] start = numbers[0..2] middle = numbers[3...-2] end = numbers[-2..] copy = numbers[..] numbers = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ] start = numbers [ 0..2 ] middle = numbers [ 3 ... -2 ] end = numbers [ -2 ..] copy = numbers [..] 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); 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 ); middle The same syntax can be used with assignment to replace a segment of an array with new values, splicing it. numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] numbers[3..6] = [-3, -4, -5, -6] numbers = [ 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ] numbers [ 3..6 ] = [ -3 , -4 , -5 , -6 ] 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; 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 ; numbers Note that JavaScript strings are immutable, and can’t be spliced.

Everything is an Expression (at least, as much as possible) You might have noticed how even though we don’t 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 return gets pushed down into each possible branch of execution in the function below. 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" 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" 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"; 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" ; eldest Even though functions will always return their final value, it’s both possible and encouraged to return early from a function body writing out the explicit return ( return value ), when you know that you’re done. Because variable declarations occur at the top of scope, assignment can be used within expressions, even for variables that haven’t been seen before: six = (one = 1) + (two = 2) + (three = 3) six = ( one = 1 ) + ( two = 2 ) + ( three = 3 ) var one, six, three, two; six = (one = 1) + (two = 2) + (three = 3); var one , six , three , two ; six = ( one = 1 ) + ( two = 2 ) + ( three = 3 ); six 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: # The first ten global properties. globals = (name for name of window)[0...10] globals = ( name for name of window )[ 0 ... 10 ] // 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); var globals , name ; globals = (( function () { var results ; results = []; for ( name in window ) { results . push ( name ); } return results ; })()). slice ( 0 , 10 ); globals As well as silly things, like passing a try / catch statement directly into a function call: alert( try nonexistent / undefined catch error "And the error is ... #{error}" ) alert ( try nonexistent / undefined catch error "And the error is ... #{error}" ) var error; alert((function() { try { return nonexistent / void 0; } catch (error1) { error = error1; return `And the error is ... ${error}`; } })()); var error ; alert (( function () { try { return nonexistent / void 0 ; } catch ( error1 ) { error = error1 ; return `And the error is ... ${ error }` ; } })()); There are a handful of statements in JavaScript that can’t be meaningfully converted into expressions, namely break , continue , and return . If you make use of them within a block of code, CoffeeScript won’t try to perform the conversion.

Operators and Aliases Because the == operator frequently causes undesirable coercion, is intransitive, and has a different meaning than in other languages, CoffeeScript compiles == into === , and != into !== . In addition, is compiles into === , and isnt into !== . You can use not as an alias for ! . For logic, and compiles to && , and or into || . Instead of a newline or semicolon, then can be used to separate conditions from expressions, in while , if / else , and switch / when statements. As in YAML, on and yes are the same as boolean true , while off and no are boolean false . unless can be used as the inverse of if . As a shortcut for this.property , you can use @property . You can use in to test for array presence, and of to test for JavaScript object-key presence. In a for loop, from compiles to the ES2015 of . (Yes, it’s unfortunate; the CoffeeScript of predates the ES2015 of .) To simplify math expressions, ** can be used for exponentiation and // performs floor division. % works just like in JavaScript, while %% provides “dividend dependent modulo”: -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) -7 % 5 == -2 -7 %% 5 == 3 tabs . selectTabAtIndex (( tabs . currentIndex - count ) %% tabs . length ) 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)); var modulo = function ( a , b ) { return ( + a % ( b = + b ) + b ) % b ; }; - 7 % 5 === - 2 ; modulo ( - 7 , 5 ) === 3 ; tabs . selectTabAtIndex ( modulo ( tabs . currentIndex - count , tabs . length )); All together now: CoffeeScript JavaScript is === isnt !== not ! and && or || true , yes , on true false , no , off false @ , this this a in b [].indexOf.call(b, a) >= 0 a of b a in b for a from b for (a of b) a ** b a ** b a // b Math.floor(a / b) a %% b (a % b + b) % b 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}" 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}" 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}`)); 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 }` ));

The Existential Operator It’s a little difficult to check for the existence of a variable in JavaScript. if (variable) … comes close, but fails for zero, the empty string, and false (to name just the most common cases). CoffeeScript’s existential operator ? returns true unless a variable is null or undefined or undeclared, which makes it analogous to Ruby’s nil? . It can also be used for safer conditional assignment than the JavaScript pattern a = a || value provides, for cases where you may be handling numbers or strings. solipsism = true if mind? and not world? speed = 0 speed ?= 15 footprints = yeti ? "bear" solipsism = true if mind ? and not world ? speed = 0 speed ? = 15 footprints = yeti ? "bear" 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"; 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" ; footprints Note that if the compiler knows that a is in scope and therefore declared, a? compiles to a != null , not a !== null . The != makes a loose comparison to null , which does double duty also comparing against undefined . The reverse also holds for not a? or unless a? . major = 'Computer Science' unless major? signUpForClass 'Introduction to Wines' major = 'Computer Science' unless major ? signUpForClass 'Introduction to Wines' var major; major = 'Computer Science'; if (major == null) { signUpForClass('Introduction to Wines'); } var major ; major = 'Computer Science' ; if ( major == null ) { signUpForClass ( 'Introduction to Wines' ); } If a variable might be undeclared, the compiler does a thorough check. This is what JavaScript coders should be typing when they want to check if a mystery variable exists. if window? environment = 'browser (probably)' if window ? environment = 'browser (probably)' var environment; if (typeof window !== "undefined" && window !== null) { environment = 'browser (probably)'; } var environment ; if ( typeof window !== "undefined" && window !== null ) { environment = 'browser (probably)' ; } The accessor variant of the existential operator ?. can be used to soak up null references in a chain of properties. Use it instead of the dot accessor . in cases where the base value may be null or undefined . If all of the properties exist then you’ll get the expected result, if the chain is broken, undefined is returned instead of the TypeError that would be raised otherwise. zip = lottery.drawWinner?().address?.zipcode zip = lottery . drawWinner ? (). address ? . zipcode var ref, zip; zip = typeof lottery.drawWinner === "function" ? (ref = lottery.drawWinner().address) != null ? ref.zipcode : void 0 : void 0; var ref , zip ; zip = typeof lottery . drawWinner === "function" ? ( ref = lottery . drawWinner (). address ) != null ? ref . zipcode : void 0 : void 0 ; For completeness: Example Definition a? tests that a is in scope and a != null a ? b returns a if a is in scope and a != null ; otherwise, b a?.b or a?['b'] returns a.b if a is in scope and a != null ; otherwise, undefined a?(b, c) or a? b, c returns the result of calling a (with arguments b and c ) if a is in scope and callable; otherwise, undefined a ?= b assigns the value of b to a if a is not in scope or if a == null ; produces the new value of a

Chaining Function Calls Leading . closes all open calls, allowing for simpler chaining syntax. $ 'body' .click (e) -> $ '.box' .fadeIn 'fast' .addClass 'show' .css 'background', 'white' $ 'body' . click ( e ) -> $ '.box' . fadeIn 'fast' . addClass 'show' . css 'background' , 'white' $('body').click(function(e) { return $('.box').fadeIn('fast').addClass('show'); }).css('background', 'white'); $ ( 'body' ). click ( function ( e ) { return $ ( '.box' ). fadeIn ( 'fast' ). addClass ( 'show' ); }). css ( 'background' , 'white' );

Destructuring Assignment 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: theBait = 1000 theSwitch = 0 [theBait, theSwitch] = [theSwitch, theBait] theBait = 1000 theSwitch = 0 [ theBait , theSwitch ] = [ theSwitch , theBait ] var theBait, theSwitch; theBait = 1000; theSwitch = 0; [theBait, theSwitch] = [theSwitch, theBait]; var theBait , theSwitch ; theBait = 1000 ; theSwitch = 0 ; [ theBait , theSwitch ] = [ theSwitch , theBait ]; theBait But it’s also helpful for dealing with functions that return multiple values. weatherReport = (location) -> # Make an Ajax request to fetch the weather... [location, 72, "Mostly Sunny"] [city, temp, forecast] = weatherReport "Berkeley, CA" weatherReport = ( location ) -> [ location , 72 , "Mostly Sunny" ] [ city , temp , forecast ] = weatherReport "Berkeley, CA" 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"); var city , forecast , temp , weatherReport ; weatherReport = function ( location ) { return [ location , 72 , "Mostly Sunny" ]; }; [ city , temp , forecast ] = weatherReport ( "Berkeley, CA" ); forecast Destructuring assignment can be used with any depth of array and object nesting, to help pull out deeply nested properties. 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 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 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); 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 ); name + "-" + street Destructuring assignment can even be combined with splats. tag = " " [open, contents..., close] = tag.split("") tag = "<impossible>" [ open , contents ..., close ] = tag . split ( "" ) var close, contents, open, ref, tag, splice = [].splice; tag = " "; ref = tag.split(""), [open, ...contents] = ref, [close] = splice.call(contents, -1); var close , contents , open , ref , tag , splice = []. splice ; tag = "<impossible>" ; ref = tag . split ( "" ), [ open , contents ] = ref , [ close ] = splice . call ( contents , - 1 ); contents.join("") 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. text = "Every literary critic believes he will outwit history and have the last word" [first, ..., last] = text.split " " text = "Every literary critic believes he will outwit history and have the last word" [ first , ..., last ] = text . split " " 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); 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 ); first + " " + last Destructuring assignment is also useful when combined with class constructors to assign properties to your instance from an options object passed to the constructor. class Person constructor: (options) -> {@name, @age, @height = 'average'} = options tim = new Person name: 'Tim', age: 4 class Person constructor : ( options ) -> { @name , @age , @height = 'average' } = options tim = new Person name : 'Tim' , age : 4 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 }); 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 }); tim.age + " " + tim.height 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 undefined —passing null will set a value of null , not the default.

Bound (Fat Arrow) Functions In JavaScript, the this 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 this will be lost. If you’re not familiar with this behavior, this Digital Web article gives a good overview of the quirks. The fat arrow => can be used to both define a function, and to bind it to the current value of this , right on the spot. This is helpful when using callback-based libraries like Prototype or jQuery, for creating iterator functions to pass to each , or event-handler functions to use with on . Functions created with the fat arrow are able to access properties of the this where they’re defined. Account = (customer, cart) -> @customer = customer @cart = cart $('.shopping_cart').on 'click', (event) => @customer.purchase @cart Account = ( customer , cart ) -> @customer = customer @cart = cart $ ( '.shopping_cart' ). on 'click' , ( event ) => @customer . purchase @cart var Account; Account = function(customer, cart) { this.customer = customer; this.cart = cart; return $('.shopping_cart').on('click', (event) => { return this.customer.purchase(this.cart); }); }; var Account ; Account = function ( customer , cart ) { this . customer = customer ; this . cart = cart ; return $ ( '.shopping_cart' ). on ( 'click' , ( event ) => { return this . customer . purchase ( this . cart ); }); }; If we had used -> in the callback above, @customer would have referred to the undefined “customer” property of the DOM element, and trying to call purchase() on it would have raised an exception. The fat arrow was one of the most popular features of CoffeeScript, and ES2015 adopted it; so CoffeeScript 2 compiles => to ES => .

Generator Functions CoffeeScript supports ES2015 generator functions through the yield keyword. There’s no function*(){} nonsense — a generator in CoffeeScript is simply a function that yields. perfectSquares = -> num = 0 loop num += 1 yield num * num return window.ps or= perfectSquares() perfectSquares = -> num = 0 loop num += 1 yield num * num return window . ps or= perfectSquares () var perfectSquares; perfectSquares = function*() { var num; num = 0; while (true) { num += 1; yield num * num; } }; window.ps || (window.ps = perfectSquares()); var perfectSquares ; perfectSquares = function* () { var num ; num = 0 ; while ( true ) { num += 1 ; yield num * num ; } }; window . ps || ( window . ps = perfectSquares ()); ps.next().value yield* is called yield from , and yield return may be used if you need to force a generator that doesn’t yield. You can iterate over a generator function using for…from . 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 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 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; }; 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 ; }; getFibonacciNumbers(10)

Async Functions ES2017’s async functions are supported through the await keyword. Like with generators, there’s no need for an async keyword; an async function in CoffeeScript is simply a function that awaits. Similar to how yield return forces a generator, await return may be used to force a function to be async. # 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 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 say "Blastoff!" countdown 3 // 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); 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 ); } return say ( "Blastoff!" ); }; countdown ( 3 );

Classes CoffeeScript 1 provided the class and extends keywords as syntactic sugar for working with prototypal functions. With ES2015, JavaScript has adopted those keywords; so CoffeeScript 2 compiles its class and extends keywords to ES2015 classes. 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() 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 () 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(); 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 (); Static methods can be defined using @ before the method name: 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 ', ' 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 ', ' 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(', '); } }; 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 ( ', ' ); } }; Teenager.say("Are we there yet?") Finally, class definitions are blocks of executable code, which make for interesting metaprogramming possibilities. In the context of a class definition, this is the class object itself; therefore, you can assign static properties by using @property: value .

Prototypal Inheritance In addition to supporting ES2015 classes, CoffeeScript provides a shortcut for working with prototypes. The :: operator gives you quick access to an object’s prototype: String::dasherize = -> this.replace /_/g, "-" String :: dasherize = -> this . replace /_/ g , "-" String.prototype.dasherize = function() { return this.replace(/_/g, "-"); }; String . prototype . dasherize = function () { return this . replace ( /_/g , "-" ); }; "one_two".dasherize()

Switch/When/Else switch statements in JavaScript are a bit awkward. You need to remember to break at the end of every case statement to avoid accidentally falling through to the default case. CoffeeScript prevents accidental fall-through, and can convert the switch into a returnable, assignable expression. The format is: switch condition, when clauses, else the default case. As in Ruby, switch statements in CoffeeScript can take multiple values for each when clause. If any of the values match, the clause runs. 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 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 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); } 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 ); } switch statements can also be used without a control expression, turning them in to a cleaner alternative to if / else chains. 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' 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' 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' 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' ; } })();

Try/Catch/Finally try expressions have the same semantics as try statements in JavaScript, though in CoffeeScript, you may omit both the catch and finally parts. The catch part may also omit the error parameter if it is not needed. try allHellBreaksLoose() catsAndDogsLivingTogether() catch error print error finally cleanUp() try allHellBreaksLoose () catsAndDogsLivingTogether () catch error print error finally cleanUp () var error; try { allHellBreaksLoose(); catsAndDogsLivingTogether(); } catch (error1) { error = error1; print(error); } finally { cleanUp(); } var error ; try { allHellBreaksLoose (); catsAndDogsLivingTogether (); } catch ( error1 ) { error = error1 ; print ( error ); } finally { cleanUp (); }

Chained Comparisons CoffeeScript borrows chained comparisons from Python — making it easy to test if a value falls within a certain range. cholesterol = 127 healthy = 200 > cholesterol > 60 cholesterol = 127 healthy = 200 > cholesterol > 60 var cholesterol, healthy; cholesterol = 127; healthy = (200 > cholesterol && cholesterol > 60); var cholesterol , healthy ; cholesterol = 127 ; healthy = ( 200 > cholesterol && cholesterol > 60 ); healthy

Block Regular Expressions 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 Perl’s /x modifier, CoffeeScript’s block regexes are delimited by /// and go a long way towards making complex regular expressions readable. To quote from the CoffeeScript source: NUMBER = /// ^ 0b[01]+ | # binary ^ 0o[0-7]+ | # octal ^ 0x[\da-f]+ | # hex ^ \d*\.?\d+ (?:e[+-]?\d+)? # decimal ///i NUMBER = /// ^ 0 b [ 0 1 ] + | ^ 0 o [ 0-7 ] + | ^ 0 x [ \ da - f ] + | ^ \ d * \ . ? \ d + ( ? : e [ +- ] ? \ d + ) ? ///i var NUMBER; NUMBER = /^0b[01]+|^0o[0-7]+|^0x[\da-f]+|^\d*\.?\d+(?:e[+-]?\d+)?/i; // binary // octal // hex // decimal var NUMBER ; NUMBER = /^0b[01]+|^0o[0-7]+|^0x[\da-f]+|^\d*\.?\d+(?:e[+-]?\d+)?/i ;

Tagged Template Literals CoffeeScript supports ES2015 tagged template literals, 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 behave accordingly: 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. upperCaseExpr = (textParts, expressions...) -> textParts.reduce (text, textPart, i) -> text + expressions[i - 1].toUpperCase() + textPart greet = (name, adjective) -> upperCaseExpr""" Hi #{name}. You look #{adjective}! """ upperCaseExpr = ( textParts , expressions ...) -> textParts . reduce ( text , textPart , i ) -> text + expressions [ i - 1 ]. toUpperCase () + textPart greet = ( name , adjective ) -> upperCaseExpr """ Hi #{name}. You look #{adjective}! """ 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}!`; }; 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 }!` ; }; greet("greg", "awesome")

Modules ES2015 modules are supported in CoffeeScript, with very similar import and export syntax: 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' 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' 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'; 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' ; Dynamic import is also supported, with mandatory parentheses: # Your browser must support dynamic import to run this example. do -> { run } = await import('./browser-compiler-modern/coffeescript.js') run ''' if 5 < new Date().getHours() < 9 alert 'Time to make the coffee!' else alert 'Time to get some work done.' ''' do -> { run } = await import ( './browser-compiler-modern/coffeescript.js' ) run ''' if 5 < new Date().getHours() < 9 alert 'Time to make the coffee!' else alert 'Time to get some work done.' ''' // Your browser must support dynamic import to run this example. (async function() { var run; ({run} = (await import('./browser-compiler-modern/coffeescript.js'))); return run(`if 5 < new Date().getHours() < 9 alert 'Time to make the coffee!' else alert 'Time to get some work done.'`); })(); ( async function () { var run ; ({ run } = ( await import ( './browser-compiler-modern/coffeescript.js' ))); return run ( `if 5 < new Date().getHours() < 9 alert 'Time to make the coffee!' else alert 'Time to get some work done.'` ); })(); Note that the CoffeeScript compiler does not resolve modules; writing an import or export statement in CoffeeScript will produce an import or export statement in the resulting output. It is your responsibility to transpile this ES2015 syntax into code that will work in your target runtimes. Also note that any file with an import or export statement will be output without a top-level function safety wrapper; in other words, importing or exporting modules will automatically trigger bare mode for that file. This is because per the ES2015 spec, import or export statements must occur at the topmost scope.

Embedded JavaScript Hopefully, you’ll 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. hi = `function() { return [document.title, "Hello JavaScript"].join(": "); }` hi = ` function () { return [ document . title , "Hello JavaScript" ]. join ( ": " ); }` var hi; hi = function() { return [document.title, "Hello JavaScript"].join(": "); }; var hi ; hi = function () { return [ document . title , "Hello JavaScript" ]. join ( ": " ); }; hi() Escape backticks with backslashes: \`​ becomes `​ . Escape backslashes before backticks with more backslashes: \\\`​ becomes \`​ . markdown = `function () { return \`In Markdown, write code like \\\`this\\\`\`; }` markdown = ` function () { return \ ` In Markdown , write code like \\\ ` this \\\ ` \ `; }` var markdown; markdown = function () { return `In Markdown, write code like \`this\``; }; var markdown ; markdown = function () { return `In Markdown, write code like \`this\`` ; }; markdown() You can also embed blocks of JavaScript using triple backticks. That’s easier than escaping backticks, if you need them inside your JavaScript block. ``` function time() { return `The time is ${new Date().toLocaleTimeString()}`; } ``` ``` function time () { return ` The time is $ { new Date (). toLocaleTimeString ()}`; } ``` function time() { return `The time is ${new Date().toLocaleTimeString()}`; } ; function time () { return `The time is ${ new Date (). toLocaleTimeString () }` ; } ; time()