CoffeeScript Syntax, Getting Started, and Best Practices Guide

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.

Installation

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:

MacOS

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

Windows

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
 
year=1998

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

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) ->
c=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);
}).call(this);

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”,
“Sherlock”,
“Moriarty”,
“Lestrade”]

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]
begin=num[0..2]
mid= num[3…-2]
over=num[-2..]
Copy=num[..]
If twodotsareused, thenumbersareincludedwhile threedotswithinthearray meansthenumberswillnot beincluded
 
Thegeneratedarrayis:
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

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

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

The compiled JavaScript is:

singer ={
 
 Male:{
 
name: "Sinatra"
 
song:  “Flymeto themoon”
 
 }
 
 Female:{
 
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'
logobject.class

Class declaration in CoffeeScript

The compiled JavaScript code is:

$('.account').attr({
"class": 'active'
});
log(object["class"]);

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"
]
 
awardMedalscontenders...
 
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 ? slice.call(arguments, 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);

Comprehensions

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
console.log(hero)
 
# 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
console.log(key)
 
# 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
"A+"
else if student.okayStuff
if student.triedHardthen "B" else "B-"
else
"C"
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:

稿源:appendto (源链) | 关于 | 阅读提示

本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » 综合编程 » CoffeeScript Syntax, Getting Started, and Best Practices Guide

喜欢 (0)or分享给?

专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录