CoffeeScript Syntax, Getting Started, and Best Practices Guide

综合编程 2017-04-06

CoffeeScript Syntax, Getting Started, and Best Practices Guide

CoffeeScript leverages the beautiful features and syntax of Ruby, Python, and Haskell to make JavaScript easier to write. CoffeeScript is one of the many popular languages (like TypeScript and Elm ) that transcompile into JavaScript. This guide will cover how to install and use CoffeeScript.


CoffeeScript runs in a Node.js environment. The objective of CoffeeScript is to provide identical features to JavaScript (but with a better syntax). Here is how to install CoffeeScript on Windows and Mac:


Node.js and npm are needed to install CoffeeScript within Terminal. CoffeeScript can be installed by running

npminstall -g coffee-script

This installs CoffeeScript globally. A local install is sometimes required when a program is to be compiled elsewhere. The code for a local install is:

npminstall --savecoffee-script


The installation process on Windows is simpler. The
installer on the Node.js website has simple steps one can follow to install Node.js. After completion, the following command will install CoffeeScript globally:

npm install -g coffee-script

To check whether it has been installed properly, we can use : coffee -v .

CoffeeScript Command Line Intro

On the command line, there are multiple flags/commands that will make it easier to work with CoffeeScript. Some of them are:

A) –no-header:

This can be declared before the code is written in order to avoid Generated by CoffeeScript header.

B) -c, –compile:

The compile command is used to compile CoffeeScript files to equivalent JavaScript files. The JavaScript file retain the name of the CoffeeScript files. For example:

coffee --compile --outputlibsrc

The command above takes CoffeeScript files from src and outputs them as JavaScript files in lib.

C) -m, –map:

This is used to map the generated JavaScript file to the source file. When the code is deployed by the client, debugging the code might become cumbersome because the code is in JavaScript and without proper line numbers and breakpoints. The map function generates the equivalent CoffeeScript code in the developer tool provided the source URL is provided with the JavaScript to enable mapping.

D) -i, –interactive:

The command launches an interactive shell from where code snippets can be compiled. This can also be done by typing in coffee in the terminal.

E) -w, –watch:

The watch command is used to compile into JavaScript every new CoffeeScript that is generated. The command has its limitations. It cannot modify folders added to the coffeescripts folder. It can only modify files.

The commands compile and watch are used in conjunction to compile to and communicate the changes to the respective CoffeeScript, like so:

coffee -w -o javascripts/ -c coffeescripts/

The -o or –output is used to write into the specified directory the generated JavaScript files.

Variables in CoffeeScript

CoffeeScript’s syntax is simpler than JavaScript. This includes removal of certain keyword declarations from the syntax as seen below.

Variables are declared without the var keyword. For example:

Square, cube

Strings, Attached

Strings are declared in a similar manner to variables, except quotes are used:

last_name = ”Moriarty”

Strings can be concatenated with the help of ‘+’ symbol between the strings, like so:

name = “James”+ last_name


Functions can be used with a special -> symbol. The symbol by itself defines an empty function. This help to make the code shorter, as the snippet shows:

add =(a,b) ->
console.log "Sum of the two numbers is: "+c
add 10,20

A function in CoffeeScript

The compiled JavaScript code is as below:

// Generated by CoffeeScript 1.10.0
(function() {
var add;
add = function(a, b) {
var c;
c = a + b;
return console.log("Sum of the two numbers is: " + c);
add(10, 20);

Compiled function in CoffeeScript

The example above shows how CoffeeScript reduces the possibility of syntactic errors when JavaScript code is written, while it retains the way they are called with parentheses.

Arrays, Slice and Splice

Arrays are declared in various forms in CoffeeScript. Some of them are show below.

The elements can be inline:

doyle =[“Watson”, “Sherlock”,“Moriarty”,“Lestrade”]

Or in separate lines:

doyle =[“Watson”,

The commas between elements can also be removed.

Arrays can also be sliced or spliced if necessary. Concretely, this means that new array segments can be formed from the arrays, like so:

num =[1,2,3,4,5,6,7,8,9]
mid= num[3…-2]
If twodotsareused, thenumbersareincludedwhile threedotswithinthearray meansthenumberswillnot beincluded
var copy, end, middle, numbers, start;
num = [1, 2, 3, 4, 5, 6, 7, 8, 9];
begin= num.slice(0, 3);
mid = num.slice(3, -2);
over = num.slice(-2);
copy = num.slice(0);


Objects in CoffeeScript are defined in a nearly identical manner. The only distinction is that the braces in CoffeeScript are implicit :

singer =
name: "Sinatra"
song:  “Flymeto themoon”
name: "Beyoncé"
song:  “SingleLadies”

The compiled JavaScript is:

singer ={
name: "Sinatra"
song:  “Flymeto themoon”
name: "Beyoncé"
song:  “SingleLadies”

CoffeeScript recognizes and actively differentiates between the objects.

Another feature in CoffeeScript (around objects) is that it can detect keywords like class without the need to declare them as separate strings within the declaration. The example below shows how this is done:

$('.account').attrclass: 'active'

Class declaration in CoffeeScript

The compiled JavaScript code is:

"class": 'active'

Class Declaration in JavaScript

(Un) Conditional Love

Most CoffeeScript conditional statements do not require parentheses, or any brackets for that matter.

Splats is a concept that is adopted from Ruby and lets one declare multiple arguments in a function, when the number of arguments is not fixed. An example is shown below:

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"
alert "Gold: " + gold
alert "Silver: " + silver
alert "The Field: " + rest

Splats in CoffeeScript

The corresponding JavaScript is:

var awardMedals, contenders, gold, rest, silver,
slice = [].slice;
gold = silver = rest = "unknown";
awardMedals = function() {
var first, others, second;
first = arguments[0], second = arguments[1], others = 3 <= arguments.length ?, 2) : [];
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.apply(null, contenders);
alert("Gold: " + gold);
alert("Silver: " + silver);
alert("The Field: " + rest);


For loops are written in the way of comprehensions, which can within themselves confine objects and arrays. For in is used to iterate through the arrays, and for of is used for objects to to the same effect as shown below:

heroes = ['leto', 'duncan', 'goku']
for heroin heroes
# Or, includingtheindex
for hero, indexin heroes
console.log('The hero at index %d is %s', index, hero)
likes =
leto: 'spice'
paul: 'chani'
duncan: 'murbella'
for keyoflikes
# Or, includingthevalue
for key, valueoflikes
console.log('%s likes %s', key, value)

For Loop in CoffeeScript

The use of comprehensions makes the code readable and compact.

Freedom of Expression

Another feature of CoffeeScript is that all written code is considered to be an expression. This means that even when there is no explicitly defined “return” function in the code, values can be returned from those expressions. For example:

grade = (student) ->
if student.excellentWork
else if student.okayStuff
if student.triedHardthen "B" else "B-"
eldest = if 24 > 21 then "Liz" else "Ike"

An expression in CoffeeScript.…

Compile into the JavaScript below:

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";

….….compiles into JavaScript with return functions.

CoffeeScript, for some, is syntactical sugar. But it can make writing thousands of lines of JavaScript much easier for developers. Initially, it might take some time getting used, but the functionality gained in return makes it worth the time invested in mastering it.

Recommended Reading:

责编内容by:appendto (源链)。感谢您的支持!


Spotlight on: The Button A well designed button can be a crucial step in taking your users on the journey...
New IT Trends IT and programming are changing every day. Not all the changes lead to the revol...
Compilers are the New Frameworks – tomdale.n... My current “investment thesis” is that what we call web frameworks are transform...
Everyone can now run JavaScript on Cloudflare with... Exactly one year ago today, Cloudflare gave me a mission: Make it so people can ...
JavaScript设计模式之面向对象编程 在JavaScript中创建一个对象很容易,首先声明一个函数保存在一个变量里。按编程习惯一般将这个变量名的首字母大写。然后内部通过this变量来添加属性或者方法...