Google News
logo
CoffeeScript Interview Questions
CoffeeScript is a lightweight programing language that compiles into JavaScript. It provides simple and easy to learn syntax avoiding the complex syntax of JavaScript. CoffeeScript is influenced by JavaScript, Ruby, YAML, Haskell, Perl, Python and has influenced MoonScript, LiveScript, and JavaScript.
 
The CoffeeScript language is designed by Jeremy Ashkenas. It was first introduced on 13 December 2009 on the git when Jeremy Ashkenas made the first git commit of CoffeeScript. On February 21, 2010, the first pure CoffeeScript compiler was released earlier the CoffeeScript compiler was in Ruby language.
It follows two rules there are :

1. Indentation rule :
* No Parenthesis
* Short Function declaration
* Define Character per line limit

2. Whitespace rule : CoffeeScript is very sensitive towards white space also no curly braces are allowed in script.
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).
 
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:
npm install --global coffeescript
This will make the coffee and cake commands available globally.
 
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:
npm install --save-dev 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 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 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.
 
There are very few breaking changes from CoffeeScript 1.x to 2; we hope the upgrade process is smooth for most projects.
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 :

Option Description
-c, --compile Compile a .coffee script into a .js JavaScript file of the same name.
-t, --transpile Pipe the CoffeeScript compiler’s output through Babel before saving or running the generated JavaScript. Requires @babel/core to be installed, and options to pass to Babel in a .babelrc file or a package.json with a babel key in the path of the file or folder to be compiled. See Transpilation.
-m, --map Generate source maps alongside the compiled JavaScript files. Adds sourceMappingURL directives to the JavaScript as well.
-M, --inline-map Just like --map, but include the source map directly in the compiled JavaScript files, rather than in a separate file.
-i, --interactive Launch an interactive CoffeeScript session to try short snippets. Identical to calling coffee with no arguments.
-o, --output [DIR] Write out all compiled JavaScript files into the specified directory. Use in conjunction with --compile or --watch.
-w, --watch Watch files for changes, rerunning the specified command when any file is updated.
-p, --print Instead of writing out the JavaScript as a file, print it directly to stdout.
-s, --stdio Pipe in CoffeeScript to STDIN and get back JavaScript over STDOUT. Good for use with processes written in other languages. An example:
cat src/cake.coffee | coffee -sc
-l, --literate Parses the code as Literate CoffeeScript. You only need to specify this when passing in code directly over stdio, or using some sort of extension-less file name.
-e, --eval Compile and print a little snippet of CoffeeScript directly from the command line. For example:
coffee -e "console.log num for num in [10..1]"
-r, --require [MODULE] require() the given module before starting the REPL or evaluating the code given with the --eval flag.
-b, --bare Compile the JavaScript without the top-level function safety wrapper.
--no-header Suppress the “Generated by CoffeeScript” header.
--nodejs The node executable has some useful options you can set, such as --debug, --debug-brk, --max-stack-size, and --expose-gc. Use this flag to forward options directly to Node.js. To pass multiple flags, use --nodejs multiple times.
--ast Generate an abstract syntax tree of nodes of the CoffeeScript. Used for integrating with JavaScript build tools.
--tokens Instead of parsing the CoffeeScript, just lex it, and print out the token stream. Used for debugging the compiler.
-n, --nodes Instead of compiling the CoffeeScript, just lex and parse it, and print out the parse tree. Used for debugging the compiler.
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 :
npm install --save-dev @babel/core
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 :
npm install --global @babel/core
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 :
npm install --save-dev @babel/preset-env  # Or --global for non-project-based usage
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
var cube, square;
​
square = function(x) {
  return x * x;
};
​
cube = function(x) {
  return square(x) * x;
};​
​
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}..."
var fill;
​
fill = function(container, liquid = "coffee") {
  return `Filling the ${container} with ${liquid}...`;
};​
​
 
In CoffeeScript, comments are denoted by the # character to the end of a line, or from ### to the next appearance of ###. Comments are ignored by the compiler, though the compiler makes its best effort at reinserting your comments into the output JavaScript after compilation.
###
Fortune Cookie Reader v1.0
Released under the MIT License
###
​
sayFortune = (fortune) ->
  console.log fortune # in bed!
​
/*
Fortune Cookie Reader v1.0
Released under the MIT License
*/
var sayFortune;
​
sayFortune = function(fortune) {
  return console.log(fortune); // in bed!
};
​
Inline ### comments make type annotations possible.
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 π"
var author, quote, sentence;
​
author = "Wittgenstein";
​
quote = `A picture is a fact. -- ${author}`;
​
sentence = `${22 / 7} is a decent approximation of π`;​
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..."
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...";​
 
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 = """
       <strong>
         cup of coffeescript
       </strong>
       """​
var html;
​
html = `<strong>
  cup of coffeescript
</strong>`;

​Double-quoted block strings, like other double-quoted strings, allow interpolation.

 

​
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
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
  }
};
​
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}!"
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}!`;
Following are the advantages of CoffeeScript :
 
Easily understandable : CoffeeScript is a shorthand form of JavaScript, its syntax is pretty simple compared to JavaScript. Using CoffeeScript, we can write clean, clear, and easily understandable codes.
 
Write less do more : For a huge code in JavaScript, we need comparatively very less number of lines of CoffeeScript.
 
Reliable : CoffeeScript is a safe and reliable programming language to write dynamic programs.
 
Readable and maintainable : CoffeeScript provides aliases for most of the operators which makes the code readable. It is also easy to maintain the programs written in CoffeeScript.
 
Class-based inheritance : JavaScript does not have classes. Instead of them, it provides powerful but confusing prototypes. Unlike JavaScript, we can create classes and inherit them in CoffeeScript. In addition to this, it also provides instance and static properties as well as mixins. It uses JavaScript's native prototype to create classes.
 
No var keyword : There is no need to use the var keyword to create a variable in CoffeeScript, thus we can avoid the accidental or unwanted scope deceleration.
 
Avoids problematic symbols : There is no need to use the problematic semicolons and parenthesis in CoffeeScript. Instead of curly braces, we can use whitespaces to differentiate the block codes like functions, loops, etc.
 
Extensive library support : In CoffeeScript, we can use the libraries of JavaScript and vice versa. Therefore, we have access to a rich set of libraries while working with CoffeeScript.
Benefits of CoffeeScript : The benefit of learning CoffeeScript is that you will explore its vast libraries including JavaScript libraries. CoffeeScript contains three things that every programmer wants : 
 
* Significant whitespace
* Straight forward class definitions and functions
* Lambda functions

Limitations : The only limitation of CoffeeScript is that it is very sensitive to whitespaces. If the proper indentation is not maintained, the error will be thrown. So, programmers need to be very careful with whitespaces.
CoffeScript TypeScript
It is best used when we want more readable code and lots of syntactic sugar. It is best used when we want optional static typing and better tool support.
It is used for server-side web applications only. It is used for both server-side and client-side web applications.
It is developed and maintained by the Open Source developer community itself under the MIT License. It is developed and maintained by Microsoft under the Apache2 License.
String interpolation is a programming language feature that allows inserting variables, arithmetic expressions, function calls directly into a string. String interpolation provides more easy and intuitive content-specification and string formatting as compared with string concatenation.
 
String interpolation in CoffeeScript : CoffeeScript provides the feature of string interpolation being inspired from Ruby language. This feature includes variables in strings and can take multi-line strings without the need of an escape character. CoffeeScript allows multiple expressions inside the interpolation.
 
String interpolation in CoffeeScript is done using double quotes(“”), a hash tag(#), and a pair of curly braces({}). The string is to be declared inside the double quotes and the variable that is to be interpolated is placed within the curly braces that are after hashtag symbol.
 
Syntax : 
name = "FtL"
message = " Hello from #{name} "
The above variable is interpolated only of the string is enclosed within double quotes (“”).
Array in CoffeeScript : Coffeescript array and array object is very similar to JavaScript array and object of array, objects may be created using curly braces or may not be its depends on programmer choice.
 
Example of Array : 
name = ["sarthak","surabhi", "tejal",
        "dipali", "girija", "devendra"] 

department = {
   id : 10,
   branch : "computer"
}

skills = 
    designer :
         name : "ali"
         surname : "bazzi"
   backend :
         name : "sunny"
          surname : "warner"
 
Map array in CoffeeScript : Array map() is used when we want to transformed each value of the array and want to get new array out of it. The map is just used to map or track the value of the array
 
Example : In the below example we have an array of objects with different values in form of key-value pair and we apply the map function on that array to get a specific object’s value. In short, we want to transform an array to get a new array out of it. 
engineers = [
  { name : "ali" , surname : "bazzi"},
  { name : "virat" , surname : "sharma"},
  { name : "sharma" , surname : "pandey"},
  { name : "paresh" , surname : "vikramadity"},
  { name : "sandip" , surname : "jain"}
]
   
names_record = engineers.map(firstname) -> firstname.name
console.log(names_record)
Output:

['ali', 'virat', 'sharma', 'paresh', 'sandip'] 
You can use CoffeeScript's destructuring assignment syntax to swap variables using the array. It allows exchanging two values without the use of a temporary variable.
In CoffeeScript, we can easily concatenate two strings by using + operator between the two strings.
 
For Example :
new_string = "Hello how are you "+"Welcome to Free Time Learn".  
console.log new_String  

On compiling the above CoffeeScript code compiler will generate corresponding javascript code as follows :  

// Generated by CoffeeScript 1.10.0  
(function() {  
  var new_string;  
  
  new_string = "Hello how are you " + "Welcome to Interview Questions";  
  
  console.log(new_String);  
  
}).call(this);  
The string object of javascript helps you work with the series of characters. String object provides various of methods to perform various operations in strings.
 
We can use the javascript library in CoffeeScript code. Hence we can use all the methods of string object in javascript.
 
Some of the methods of string object :
 
* charAt() : This method returns the character at the given index value of a string object.

*
charCodeAt() : This method returns the Unicode value of the character at the given index.

*
concat() : This method combines two substrings and returns a superstring.

*
indexOf() : This method returns the index of calling string having the first occurrence of a specified value, It will return -1 if not found.

*
lastIndexOf() : This method returns the index of calling string having the last occurrence of a specified value, It will return -1 if not found.

*
localeCompare() : This method returns a number representing whether a reference string comes before or after or is the same as given string in sort order.

*
match() : This method is used to match a regular expression against a string.

*
search() : This method executes a search for a match between the regular expressions in a specified string.

*
slice() : Extract the section of a string object and returns a new string object.

*
split() : Splits a string object into the array of strings by separating the string into substrings.

*
substr() : This method returns the calling string beginning at the specified location through the specified number of characters.

*
toLocaleLowerCase() : Converts the calling string into the lower case while respecting the current locale.

*
toLocaleUpperCase() : Converts calling string into the upper case while respecting the current locale.

*
toLowerCase() : Returns calling string in lower case.

*
ToUpperCase() : Returns calling string in upper case.
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()​
var changeNumbers, inner, outer;
​
outer = 1;
​
changeNumbers = function() {
  var inner;
  inner = -1;
  return outer = 10;
};
​
inner = changeNumbers();​
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.
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
var date, mood;
​
if (singing) {
  mood = greatlyImproved;
}
​
if (happy && knowsIt) {
  clapsHands();
  chaChaCha();
} else {
  showIt();
}
​
date = friday ? sue : jill;
The CoffeeScript provides a feature known as splat which is used to pass multiple arguments to a function.
 
We can use splats in functions by placing three dots (...) after the variable name.
 
Example :
indian_team = (first, second, others...) ->  
  Captain = first  
  WiseCaptain = second  
  team  = others  
  console.log "Captain: " +Captain  
  console.log "Wise captain: " +WiseCaptain  
  console.log "Other team members: " +team  
  
#Passing 4 arguments  
console.log "############## Four Players ############"  
indian_team "Mahendra Singh Dhoni", "Virat Kohli", "Shikhar Dhawan", "Rohit Sharma"  
  
#Passing 6 arguments  
console.log "############## Six Players ############"  
indian_team "Mahendra Singh Dhoni", "Virat Kohli", "Shikhar Dhawan", "Rohit Sharma", "Gurkeerat Singh Mann", "Rishi Dhawan"  
    
#Passing full squad  
console.log "############## Full squad #############"  
indian_team "Mahendra Singh Dhoni", "Virat Kohli", "Shikhar Dhawan", "Rohit Sharma", "Gurkeerat Singh Mann", "Rishi Dhawan", "Ravindra Jadeja", "Axar Patel", "Jasprit Bumrah", "Umesh Yadav", "Harbhajan Singh", "Ashish Nehra", "Hardik Pandya", "Suresh Raina", "Yuvraj Singh", "Ajinkya Rahane"  
Explanation of the above example :
 
In the above case of spats, multiple arguments were being passed to the function. By placing three dots after the argument list of the function indian_team. In the first pass we have passed four arguments to the function, in the second pass we have passed six arguments to the function, and in the last pass, we had passed the names of the full squad to the function.
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 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);
  }
}​

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.
The splats with tailing argument refer to the argument placed after the splat argument.
 
Example :
indian_team = (first, second, others...., last) ->  
  Captain = first  
  WiseCaptain = second  
  team  = others  
  Wicketkeeper =last  
  console.log "Captain: " +Captain  
  console.log "Wise captain: " +WiseCaptain  
  console.log "Wicket keeper is:"+last  
  console.log "Other team members: " +team    
    
squad = [  
   "Mahendra Singh Dhoni"  
   "Virat Kohli"  
   "Shikhar Dhawan"  
   "Rohit Sharma"     
   "Gurkeerat Singh Mann"  
   "Rishi Dhawan"  
   "R Ashwin"  
   "Ravindra Jadeja"  
   "Axar Patel"  
   "Jasprit Bumrah"  
   "Umesh Yadav"  
   "Harbhajan Singh"  
   "Ashish Nehra"  
   "Hardik Pandya"  
   "Suresh Raina"  
   "Yuvraj Singh"  
   "Ajinkya Rahane"  
 ]​
  
In the above example of using tailing with splats, we have placed an additional argument to the argument list of the indian_team function.
We can use the javascript library in CoffeeScript code. Hence we can use all the methods of math object in javascript.
 
Some math function present in the math object :
 
* abs() : This function returns the absolute value of a number.

*
acos() : This function returns arccosine (in radians) of a number.

*
asin() : This function returns arcsine (in radians) of a number.

*
atan() : This function returns arctangent (in radians) of a number.

*
atan2() : This function returns arctangent of the quotient of its arguments.

*
ceil() : This function returns the smallest integer greater than or equal to the given number.

*
cos() : This function returns the cosin of the given number.

*
exp() : This function returns EN, Where N is the argument, and E is the Euler's constant, the base of the natural logarithm.

*
floor() : This function returns the largest integer less than equal to the number.

*
log() : This function returns natural logarithm (base E) of a number.

*
max() : This function returns largest of zero or more numbers.

*
min() : This function returns the smallest of zero or more numbers.

*
pow() : This function returns the base exponent of the given number.

*
random() : This function returns the pseudo-random number between 0 and 1.

*
round() : This function returns the value of the number rounded to the nearest integer.

*
sin() : This function returns the sine of the given number.

*
sqrt() : This function returns the square root of the specified number.

*
tan() : This function returns the tangent of the specified number.
Clone function is useful in creating completly new object by :

* Creating a new object as the source object.
* Copying all attributes from the source object to the new object.
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[..]​
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);​
​
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]​
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;

Note that JavaScript strings are immutable, and can’t be spliced.

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)

 

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));​

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
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​
// 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);
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()
​
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 ', '
​
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(', ');
  }
​
};​
​
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.
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.prototype.dasherize = function() {
  return this.replace(/_/g, "-");
};
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) {
  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'
​
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'
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()
​
var error;
​
try {
  allHellBreaksLoose();
  catsAndDogsLivingTogether();
} catch (error1) {
  error = error1;
  print(error);
} finally {
  cleanUp();
}
​
 
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
​
var NUMBER;
​
NUMBER = /^0b[01]+|^0o[0-7]+|^0x[\da-f]+|^\d*\.?\d+(?:e[+-]?\d+)?/i; // binary
// octal
// hex
// decimal
ES2015 modules are supported in CoffeeScript, with very similar import and export syntax :
import './local-file.js' # Must be the filename of the generated file
import 'package'
​
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'
​
import dates from './calendar.json' assert { type: 'json' }
​
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'
export { version } from './package.json' assert { type: 'json' }
import './local-file.js';
​
import 'package';
​
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';
​
import dates from './calendar.json' assert {
  type: 'json'
};
​
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';
​
export {
  version
} from './package.json' assert {
    type: 'json'
  };
 
Dynamic import is also supported in CoffeeScript, 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.'
  '''
// 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.'`);
})();
​
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(": ");
}`
​
var hi;
​
hi = function() {
  return [document.title, "Hello JavaScript"].join(": ");
};
Escape backticks with backslashes : \`​ becomes `​.
 
Escape backslashes before backticks with more backslashes : \\\`​ becomes \`​.
markdown = `function () {
  return \`In Markdown, write code like \\\`this\\\`\`;
}`
​
var markdown;
​
markdown = function () {
  return `In Markdown, write code like \`this\``;
};​
​
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()}`;
}
;
JSX is JavaScript containing interspersed XML elements. While conceived for React, it is not specific to any particular library or framework.
 
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 Babel with the React JSX transform. CoffeeScript does not output React.createElement 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.
 
Just like in JSX and HTML, denote XML tags using < and >. You can interpolate CoffeeScript code inside a tag using { and }. To avoid compiler errors, when using < and > to mean “less than” or “greater than,” you should wrap the operators in spaces to distinguish them from XML tags. So i < len, not i<len. 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.
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>
​
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>;
};
Older plugins or forks of CoffeeScript supported JSX syntax and referred to it as CSX or CJSX. They also often used a .cjsx file extension, but this is no longer necessary; regular .coffee will do.