Coffeescript Tutorial
Coffeescript Tutorial
Audience
This tutorial has been prepared for beginners to help them understand the basic functionality of
CoffeeScript to build dynamic webpages and web applications.
Prerequisites
For this tutorial, it is assumed that the readers have a prior knowledge of HTML coding and
JavaScript. It would help if the reader has some prior exposure to object-oriented programming
concepts and a general idea on creating online applications.
Try the following example using the Try it option available at the top right corner of the below
sample code box −
All the content and graphics published in this e-book are the property of Tutorials Point (I) Pvt.
Ltd. The user of this e-book is prohibited to reuse, retain, copy, distribute or republish any
contents or a part of contents of this e-book in any manner without written consent of the
publisher.
We strive to update the contents of our website and tutorials as timely and as precisely as
possible, however, the contents may contain inaccuracies or errors. Tutorials Point (I) Pvt. Ltd.
provides no guarantee regarding the accuracy, timeliness or completeness of our website or its
contents including this tutorial. If you discover any errors on our website or in this tutorial,
please notify us at [email protected]
i
CoffeeScript
Table of Contents
About the Tutorial ..................................................................................................................................... i
Audience.................................................................................................................................................... i
Prerequisites ............................................................................................................................................. i
Limitations of CoffeeScript..................................................................................................................... 2
ii
CoffeeScript
No Parentheses ..................................................................................................................................... 15
iii
CoffeeScript
unless…then Statement........................................................................................................................ 61
Multi-line Functions............................................................................................................................... 83
iv
CoffeeScript
localeCompare() Method....................................................................................................................... 99
vii
CoffeeScript
ix
1. CoffeeScript – Overview CoffeeScript
At present, JavaScript is the fastest mainstream dynamic language available, and it is known as
the lingua franca of the web. It is developed by Brendan Eich in the year of 1995 in 10 days.
Because of its effective features, JavaScript became popular and went global quickly. It was
there in lab for a very less time, which was not enough to polish the language. May be for this
reason, inspite of its good parts, JavaScript has a bunch of design errors and it bagged a bad
reputation of being a quirky language.
What is CoffeeScript ?
CoffeeScript is a lightweight language based on Ruby and Python which transcompiles
(compiles from one source language to another) into JavaScript. It provides better syntax
avoiding the quirky parts of JavaScript, still retaining the flexibility and beauty of the language.
Advantages of CoffeeScript
Following are the advantages of CoffeeScript −
Write less do more − For a huge code in JavaScript, we need comparatively very less
number of lines of CoffeeScript.
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.
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.
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.
History of CoffeeScript
CoffeeScript is developed by Jeremy Ashkenas. It was first committed in Git On December
13, 2009.
1
CoffeeScript
In March 2010, the CoffeeScript compiler was replaced; this time instead of Ruby, they
used CoffeeScript itself.
And in the same year, CoffeeScript 1.0 was released and at the time of release, it was
one of the most wanted projects of the Git hub.
Limitations of CoffeeScript
Sensitive to whitespaces − CoffeeScript is very sensitive to whitespaces, so programmers
need to be very careful while providing indentations. If we do not maintain proper indentation,
the entire code may go wrong.
Step 1
Click on the following link www.tutorialspoint.com. You will be directed to the homepage of our
website.
Step 2
Click on the button named CODING GROUND that is located at the top right corner of the
homepage as highlighted in the snapshot given below.
2
CoffeeScript
Step 3
This will lead to our CODING GROUND section which provides online terminals and IDEs for
about 135 programming languages. Open CoffeeScript IDE in the Online IDEs section which is
shown in the following snapshot.
Step 4
If you paste your CoffeeScript code in main.coffee (You can change the file name) and click
the Preview button, then you can see the compiled JavaScript in the console as shown in the
following snapshot.
3
2. CoffeeScript – Environment CoffeeScript
The Compiler of the latest versions of CoffeeScript is written in CoffeeScript itself. To run
CoffeeScript files in your system without a browser, you need a JavaScript runtime.
Node.js
Node.js is a JavaScript framework which is used to develop network server applications. It also
acts as a bridge between JavaScript and the Operating System.
Installing Node.js
Here are the steps to download and install Node.js in your system.
Step 1
Visit the nodejs homepage and download its stable version for windows by clicking on the button
hilighted in the snapshot given below.
4
CoffeeScript
Step 2
On clicking, a .msc file named node-v5.50-x64 will be downloaded into your system, run the
downloaded file to start the Node.js set-up. Here is the snapshot of the Welcome page of No.js
set-up wizard.
Step 3
Click on the Next button in the Welcome page of the Node.js set-up wizard which will lead you
to the End-user License Agreement page. Accept the license agreement and click on the Next
button as shown below.
5
CoffeeScript
Step 4
On the next page, you need to set the destination folder to the path where you want to install
Node.js. Change the path to the required folder and click on the Next button.
Step 5
In the Custom setup page, select the Node.js runtime to install node.exe file and click Next.
6
CoffeeScript
Step 6
Finally, click on the Install button which will start the Node.js installation.
Click on the Finish button of the Node.js set-up wizard as shown below to complete the Node.js
installation.
7
CoffeeScript
Installing CoffeeScript
Node.js provides you a command prompt (Node.js command prompt). You can install
CoffeeScript globally by entering the following command in it.
On executing the the above command, CoffeeScript will be installed in your system by producing
the following output
Verification
You can verify the installation of the CoffeeScript by typing the following command.
c:\> coffee -v
On successful installation, this command gives you the version of CoffeeScript as shown below.
8
3. CoffeeScript – Command-line Utility CoffeeScript
On installing CoffeeScript on Node.js, we can access the coffee-command line utility. In here,
the coffee command is the key command. Using various options of this command, we can
compile and execute the CoffeeScript files.
You can see the list of options of the coffee command using its -h or --help option. Open
the Node.js command prompt and execute the following command in it.
c:\>coffee -help
This command gives you the list of various options of the coffee, along with the description of
the operation performed by each of them as shown below.
c:\>coffee -c filename.coffee
9
CoffeeScript
Example
Suppose there is a file in your system with the following CoffeeScript code which prints a
message on the console.
name = "Raju"
console.log "Hello"+name+" Welcome to Tutorilspoint"
Note − The console.log() function prints the given string on the consloe.
To compile the above code, save it in a file with the name sample.coffee. Open the Node.js
command prompt. Browse through the path where you have saved the file and compile it using
the -c option of the coffee command of the coffee command-line utility as shown below.
On executing the above command, the CoffeeScript compiler compiles the given file
(sample.coffee) and saves it in the current location with a name sample.js as shown below.
If you open the sample.js file, you can observe the generated JavaScript as shown below.
}).call(this);
10
CoffeeScript
Example
For example, let us execute the sample.coffee file. For this, open the Node.js command prompt.
Browse through the path where you have saved the file and execute the file by directly passing
its name to the coffee command as shown below.
You can watch and compile a file simultaneously using the -wc option as shown below. When we
use this option, the file will be recompiled each time you make changes in your script.
Example
Suppose we have compiled a file named sample.coffee using the -wc option and we modified
the script thrice. Each time we change the script, the .coffee file is recompiled leaving the
Node.js command prompt as shown below.
11
CoffeeScript
Example
Let us save the JavaScript code of the sample.coffee file in a folder named data in the E drive
using the -o option by executing the following command in the command prompt.
Following is the snapshot of the given folder after executing the above command. Here you can
observe the JavaScript file of the sample.coffee
c:\>coffee -p file_name
Example
For example, you can print the compiled JavaScript code of the sample.coffee file on the console
using the -p option as shown below.
12
CoffeeScript
Using this shell, we can assign values to variables, create functions, and evaluate results. As
shown in the following screenshot, if we call functions in REPL, it prints the value of the function.
If we give an expression to it, it evaluates and prints the result of the expression. And if we
simply type the statements in it, it prints the value of the last statement.
13
CoffeeScript
In RPEL, you can access multiple line mode by pressing ctrl+v where you can evaluate the code
with multiple lines (like functions) and you can get back to REPL mode from it by
pressing ctrl+v again. Here is an example usage of the multi line mode.
<script src="http://jashkenas.github.com/coffee-script/extras/coffee-script.js"
type="text/javascript" charset="utf-8"></script>
<script type="text/coffeescript">
# Some CoffeeScript
</script>
But for this, we have to import the library in each application and the CoffeeScript code will be
interpreted line by line before the output is shown. This will slow down your applications,
therefore this approach is not recommended.
Therefore, to use CoffeeScript in your applications, you need to pre-compile them using the
Coffee command-line utility and then you can use the generated JavaScript in your applications.
14
4. CoffeeScript – Syntax CoffeeScript
In the previous chapter, we have seen how to install CoffeeScript. In this chapter, let us check
out the syntax of CoffeeScript.
The syntax of CoffeeScript is more graceful when compared to the syntax of JavaScript. It avoids
the troublesome features like curly braces, semicolons, and variable decelerations.
CoffeeScript Statements
Unlike many other programming languages like C, C++, and Java, the statements in CoffeeScript
do not end with semicolons (;). Instead of that, every new line is considered as a separate
statement by the CoffeeScript compiler.
Example
Here is an example of a CoffeeScript statement.
name = "Javed"
age = 26
In the same way, we can write two statements in a single line by separating them using
semicolon as shown below.
name = "Javed";age = 26
While creating variables in CoffeeScript, there is no need to declare them using the var keyword.
We can directly create a variable just by assigning a value to it as shown below.
name = "Javed"
age = 20
No Parentheses
In general, we use parenthesis while declaring the function, calling it, and also to separate the
code blocks to avoid ambiguity. In CoffeeScript, there is no need to use parentheses, and while
creating functions, we use an arrow mark (->) instead of parentheses as shown below.
15
CoffeeScript
Still, we have to use parentheses in certain scenarios. While calling functions without
parameters, we will use parentheses. For example, if we have a function named my_function in
CoffeeScript, then we have to call it as shown below.
my_function()
In the same way, we can also separate the ambiguous code using parentheses. If you observe
the following example, without braces, the result is 2233 and with braces, it will be 45.
No Curly Braces
In JavaScript, for the block codes such as functions, loops, and conditional statements, we use
curly braces. In CoffeeScript, there is no need to use curly braces. Instead, we have to maintain
proper indentations (white spaces) within the body. This is the feature which is inspired from
the Python language.
Following is an example of a function in CoffeeScript. Here you can observe that instead of curly
braces, we have used three whitespaces as indentation to separate the body of the function.
myfunction = ->
name = "John"
alert "Hello"+name
CoffeeScript Comments
In any programming language, we use comments to write description about the code we have
written. These comments are not considered as the part of the programs. The comments in
CoffeeScript are similar to the comments of Ruby language. CoffeeScript provides two types of
comments as follows −
Single-line Comments
Whenever we want to comment a single line in CoffeeScript, we just need to place a hash tag
before it as shown below.
Every single line that follows a hash tag (#) is considered as a comment by the CoffeeScript
compiler and it compiles the rest of the code in the given file except the comments.
Multiline Comments
Whenever we want to comment more than one line in CoffeeScript (multiple lines), we can do
that by wrapping those lines within a pair of triple hash tags as shown below.
###
These are the multi line comments in CoffeeScript
We can write as many number of lines as we want
16
CoffeeScript
const static if by
__bind in class on
17
5. CoffeeScript – Data types CoffeeScript
As CoffeeScript compiles line by line to JavaScript, the data types provided by CoffeeScript are
same as JavaScript. Except for the fact that CoffeeScript adds some additional essence.
Strings − The String data type represents a group of characters in general and we
represent a string value with in-between double quotes (" ")
Example: "Raj", "Rahman"
Boolean− Boolean data type represents one bit of information. There are only two
possible values: true and false.
Arrays− The Array object lets you store multiple values in a single variable. It stores a
fixed-size sequential collection of elements of the same type
Example: student = ["Rahman","Ramu","Ravi","Robert"]
Objects− The Objects in CoffeeScript are similar to those in JavaScript these are
collection of the properties. Where a property includes a key and a value separated by a
semi colon (:). In short, CoffeeScript objects are a collection of key-value pairs. For
example,
student = {name: "Mohammed", age: 24, phone: 9848022338 }
Null − A variable that is defined and does not hold any value is considered and null. This
is similar to the null value in JavaScript.
We will cover the data types Arrays and Objects in detail in separate chapters.
18
6. CoffeeScript – Variables CoffeeScript
Variables are nothing but named containers. You can place data into these containers and then
refer to the data using the name of its container.
CoffeeScript Variables
In JavaScript, before using a variable, we need to declare and initialize it (assign value). Unlike
JavaScript, while creating a variable in CoffeeScript, there is no need to declare it using the var
keyword. We simply create a variable just by assigning a value to a literal as shown below.
Example
In the following CoffeeScript code, we have defined two variables name and age, of string and
number data types respectively. Save it in a file with the name variable_example.coffee
name = "Javed"
age = 25
On compiling, a JavaScript file named variable_example.js will be generated with the following
content. Here you can observe that the compiler declared the variables (age and name) using
the var keyword on behalf of us.
(function() {
var age, name;
name = "Javed";
age = 25;
}).call(this);
Variable Scope
The scope of a variable is the region of your program in which it is defined. JavaScript and
CoffeeScript variables have only two scopes.
Global Variables − A global variable has global scope which means it can be used
anywhere in your JavaScript code.
19
CoffeeScript
Local Variables − A local variable will be visible only within a function where it is defined.
Function parameters are always local to that function.
In the above example, we have created a variable named i in the global space and assigned the
value 10 to it. And within the function, on an attempt to create a local variable with the same
name, we have declared as i=20; without var keyword. Since we missed the var keyword, the
value of global variable i is reassigned to 20.
For this reason, it is recommended to declare variables using the var keyword.
(function() {
var age, name;
name = "javed";
20
CoffeeScript
age = 20;
}).call(this);
Anyway, if we want, we can declare a variable with global namespace. We can do it explicitly as
shown below.
obj = this
obj.age = 30
You should not use any of the CoffeeScript reserved keywords as a variable name. These
keywords are mentioned in the next section. For example, break or Boolean variable
names are not valid.
CoffeeScript variable names should not start with a numeral (0-9). They must begin with
a letter or an underscore character. For example, 123test is an invalid variable name but
_123test is a valid one.
CoffeeScript variable names are case-sensitive. For example, Name and name are two
different variables.
21
7. CoffeeScript – Operators CoffeeScript
An operator is a symbol that tells the compiler to perform specific mathematical or logical
functions. Let us take a simple expression 4 + 5 is equal to 9. Here 4 and 5 are called
operands and ‘+’ is called the operator.
The operators provided by CoffeeScript are same as in JavaScript except a few differences. There
are some problematic operators in JavaScript. CoffeeScript either removed them or modified
their functionality and it also introduced some new operators.
CoffeeScript Aliases
In addition to operators, CoffeeScript also provides aliases. CoffeeScript provides aliases to
various operators and symbols in order to make your CoffeeScript code readable and more user
friendly.
Arithmetic Operators
Comparison Operators
Logical (or Relational) Operators
Assignment Operators
Let us have a look at all the operators and aliases of CoffeeScript one by one.
Arithmetic Operators
CoffeeScript supports the following arithmetic operators. Assume variable A holds 10 and
variable B holds 20, then –
Show Examples
Sr.No Operator and Description Example
+ (Addition)
1 A + B = 30
Adds two operands
- (Subtraction)
2 A - B = -10
Subtracts the second operand from the first
* (Multiplication)
3 A * B = 200
Multiply both operands
/ (Division)
4 B/A=2
Divide the numerator by the denominator
% (Modulus)
5 B%A=0
Outputs the remainder of an integer division
22
CoffeeScript
++ (Increment)
6 A++ = 11
Increases an integer value by one
-- (Decrement)
7 A-- = 9
Decreases an integer value by one
Example
The following example shows how to use arithmetic operators in CoffeeScript. Save this code in
a file with name airthmatic_example.coffee
a = 33
b = 10
c = "test"
console.log "The value of a + b = is"
result = a + b
console.log result
result = a - b
console.log "The value of a - b = is "
console.log result
a = ++a
console.log "The value of ++a = is"
result = ++a
console.log result
23
CoffeeScript
b = --b
console.log "The value of --b = is"
result = --b
console.log result
Open the command prompt and compile the .coffee file as shown below.
result = a - b;
console.log("The value of a - b = is ");
console.log(result);
a = ++a;
24
CoffeeScript
b = --b;
console.log("The value of --b = is");
result = --b;
console.log(result);
}).call(this);
Now, open the command prompt again and run the CoffeeScript file as shown below.
The value of a + b = is
43
The value of a - b = is
23
The value of a / b = is
3.3
The value of a % b = is
3
The value of a + b + c = is
43test
The value of ++a = is
35
The value of --b = is
8
Comparison Operators
JavaScript supports the following comparison operators. Assume variable A holds 10 and
variable B holds 20, then –
25
CoffeeScript
Show Examples
Sr.No Operator and Description Example
= = (Equal)
(A == B) is not
1 Checks if the value of two operands are equal or not, if yes, then true.
the condition becomes true.
!= (Not Equal)
2 Checks if the value of two operands are equal or not, if the (A != B) is true.
values are not equal, then the condition becomes true.
Checks if the value of the left operand is greater than or equal (A >= B) is not
5
to the value of the right operand, if yes, then the condition true.
becomes true.
6 Checks if the value of the left operand is less than or equal to (A <= B) is true.
the value of the right operand, if yes, then the condition
becomes true.
Example
The following code shows how to use comparison operators in CoffeeScript. Save this code in a
file with name comparison_example.coffee
a = 10
b = 20
console.log "The result of (a == b) is "
result = a == b
console.log result
console.log result
Open the command prompt and compile the comparison_example.coffee file as shown below.
result = a !== b;
console.log(result);
}).call(this);
Now, open the command prompt again and run the CoffeeScript file as shown below.
The result of (a == b) is
false
The result of (a < b) is
true
The result of (a > b) is
false
The result of (a != b) is
true
The result of (a >= b) is
true
The result of (a <= b) is
false
Following table shows the aliases for few of the Comparison operators. Suppose A holds 20and
variable B holds 20.
Show Examples
Operator Alias Example
28
CoffeeScript
Example
The following code shows how to use aliases for comparison operators in CoffeeScript. Save this
code in a file with name comparison_aliases.coffee
a = 10
b = 20
console.log "The result of (a is b) is "
result = a is b
console.log result
Open the command prompt and compile the comparison_example.coffee file as shown below.
a = 10;
b = 20;
result = a === b;
console.log(result);
result = a !== b;
29
CoffeeScript
console.log(result);
}).call(this);
Now, open the command prompt again and run the CoffeeScript file as shown below.
The result of (a is b) is
false
The result of (a isnt b) is
true
Logical Operators
CoffeeScript supports the following logical operators. Assume variable A holds 10 and
variable B holds 20, then −
Show Examples
Sr.No Operator and Description Example
|| (Logical OR)
2 If any of the two operands are non-zero, then the condition (A || B) is true.
becomes true.
! (Logical NOT)
3 Reverses the logical state of its operand. If a condition is true, ! (A && B) is false.
then the Logical NOT operator will make it false.
Example
Following is the example demonstrating the use of logical operators in coffeeScript. Save this
code in a file with name logical_example.coffee.
a = true
b = false
30
CoffeeScript
Open the command prompt and compile the .coffee file as shown below.
}).call(this);
31
CoffeeScript
Now, open the command prompt again and run the CoffeeScript file as shown below.
The following table shows the aliases for some of the logical operators. Suppose X holds true and
variable Y holds false.
Show Examples
Operator Alias Example
|| (Logical OR)
or X or Y gives you true
! (not x)
not not X gives you false
Example
The following example demonstrates the use aliases for logical operators in CoffeeScript. Save
this code in a file with name logical_aliases.coffee.
a = true
b = false
32
CoffeeScript
Open the command prompt and compile the .coffee file as shown below.
}).call(this);
Now, open the command prompt again and run the CoffeeScript file as shown below.
33
CoffeeScript
Bitwise Operators
CoffeeScript supports the following bitwise operators. Assume variable A holds 2 and
variable B holds 3, then −
Show Examples
Sr.No Operator and Description Example
| (BitWise OR)
2 It performs a Boolean OR operation on each bit of its integer (A | B) is 3.
arguments.
^ (Bitwise XOR)
~ (Bitwise Not)
4 It is a unary operator and operates by reversing all the bits in the (~B) is -4.
operand.
Example
The following example demonstrates the usage of bitwise operators in CoffeeScript. Save this
code in a file with name bitwise_example.coffee
a = 2 # Bit presentation 10
b = 3 # Bit presentation 11
result = a & b
console.log result
Open the command prompt and compile the .coffee file as shown below.
35
CoffeeScript
}).call(this);
Now, open the command prompt again and run the CoffeeScript file as shown below.
Assignment Operators
CoffeeScript supports the following assignment operators −
Show Examples
Sr.No Operator and Description Example
= (Simple Assignment )
1 C = A + B will assign the value of
Assigns values from the right side operand to the A + B into C
left side operand
Note − Same logic applies to Bitwise operators so they will become like <<=, >>=, >>=, &=,
|= and ^=.
Example
The following example demonstrates the usage of assignment operators in CoffeeScript. Save
this code in a file with name assignment _example.coffee
a = 33
b = 10
37
CoffeeScript
console.log result
Open the command prompt and compile the .coffee file as shown below.
result = a += b;
console.log(result);
}).call(this);
Now, open the command prompt again and run the CoffeeScript file as shown below.
39
CoffeeScript
The == operator in JavaScript is type coercive, i.e., if the types of the two operands in an
operation are different, then the data type of one of the operator is converted into other and
then both are compared.
CoffeeScript avoids this undesirable coercion, it compiles the == operator in to the strict
comparison operator of JavaScript ===.
If we compare two operands using ===, then it returns true, only if both the value and
datatypes of them are equal, else it returns false.
Example
Consider the following example. Here we have two variables a and b. a holds the value 21 of
integer type and b holds the same value, but it is of string type. In CoffeeScript, when we
compare a and b, the result will be false. (Since the == operator of CoffeeScript is converted to
=== operator of JavaScript)
a=21
b="21"
result = 21=='21'
console.log result
result = a === b;
console.log(result);
}).call(this);
false
40
CoffeeScript
Example
Given below is an example of the existential operator. Here we have three variables, namely
name, age, and subject and we are verifying the existence of the variables name and phone
using existential operator.
name="Ramu"
age=24
subject="Engineering"
verify_name = name?
verify_phone = phone?
console.log verify_name
console.log verify_phone
subject = "Engineering";
verify_name = name != null;
verify_phone = typeof phone !== "undefined" && phone !== null;
console.log(verify_name);
console.log(verify_phone);
}).call(this);
true
false
Note − We have an accessor variant of the existential operator ?. We can use it instead of
the . operator to find out the null references.
41
CoffeeScript
Chained Comparisons
As in Python, we can use a chain of comparison operators in a single expression in CoffeeScript.
Example
Following is an example of using chained comparison.
score = 70
passed = 100 > score > 40
console.log passed
On compiling, the example CoffeeScript gives you the following JavaScript code.
score = 70;
console.log(passed);
}).call(this);
If you execute the above CoffeeScript code, it produces the following output.
true
Note − CoffeeScript removes the ternary operator; instead of it, we can use the inline if
statement.
CoffeeScript Aliases
In general, CoffeeScript provides aliases to various operators and symbols in order to make your
CoffeeScript code readable and more user friendly. Following are the aliases provided by
CoffeeScript.
42
CoffeeScript
"or" operator || or
Inverse of if ! if unless
Exponentiation a**b
Example
The following example shows how to use aliases in CoffeeScript –
a=21; b=21
x = true; y = false
console.log a is b
console.log a isnt b
console.log x and y
console.log x or y
console.log yes or no
console.log on or off
console.log a**b
43
CoffeeScript
console.log a//b
console.log a%%b
On compiling the above example, it gives you the following JavaScript code.
a = 21;
b = 21;
x = true;
y = false;
console.log(x || y);
console.log(true || false);
console.log(true || false);
console.log(Math.pow(a, b));
console.log(Math.floor(a / b));
console.log(modulo(a, b));
44
CoffeeScript
}).call(this);
If you execute the above CoffeeScript file, it produces the following output −
true
false
false
true
true
true
5.842587018385982e+27
1
0
45
8. CoffeeScript – Conditionals CoffeeScript
While programming, we encounter some scenarios where we have to choose a path from a given
set of paths. In such situations, we need conditional statements. Conditional statements help us
take decisions and perform right actions.
Following is the general form of a typical decision-making structure found in most of the
programming languages.
JavaScript supports the if statement (including its variants) and switch statement. In addition
to the conditionals available in JavaScript, CoffeeScript includes the unless statement, the
negation of if, and even more.
if statement
1
An if statement consists of a Boolean expression followed by one or more statements.
These statements execute when the given Boolean expression is true.
if...else statement
2 An if statement can be followed by an optional else statement, which executes when the
Boolean expression is false.
unless statement
3 An unless statement is similar to if with a Boolean expression followed by one or more
statements except. These statements execute when a given Boolean expression is false.
4 unless...else statement
46
CoffeeScript
switch statement
5
A switch statement allows a variable to be tested for equality against a list of values.
if Statement
The if statement is the fundamental control statement that allows us to make decisions and
execute statements conditionally.
The if statement in CoffeeScript is similar to that we have in JavaScript. The difference is that
while writing an if statement in CoffeeScript, there is no need to use parentheses to specify the
Boolean condition. Also, instead of curly braces, we separate the body of the conditional
statement by using proper indentations.
Syntax
Given below is the syntax of the if statement in CoffeeScript. It contains a keyword if, soon after
the if keyword, we have to specify a Boolean expression which is followed by a block of
statements. If the given expression is true, then the code in the if block is executed.
if expression
Statement(s) to be executed if expression is true
Flow Diagram
47
CoffeeScript
Example
The following example demonstrates how to use the if statement in CoffeeScript. Save this code
in a file with the name if_example.coffee
name = "Ramu"
score = 60
if score>=40
console.log "Congratulations you have passed the examination"
Open the command prompt and compile the .coffee file as shown below.
name = "Ramu";
score = 60;
}).call(this);
Now, open the command prompt again and run the CoffeeScript file as shown below.
if…else Statement
The if statement executes the given block of code if the specified Boolean expression is true.
What if the Boolean expression is false?
48
CoffeeScript
The 'if...else' statement is the next form of control statement that allows CoffeeScript to execute
statements in a more controlled way. It will have an else block which executes when the Boolean
expression is false.
Syntax
Given below is the syntax of the if-else statement in CoffeeScript. If the given expression is true,
then the statements in the if block are executed and if it is false the statements in the else block
are executed.
if expression
Statement(s) to be executed if the expression is true
else
Statement(s) to be executed if the expression is false
Flow Diagram
Example
The following example demonstrates how to use the if-else statement in CoffeeScript. Save this
code in a file with name if_else_example.coffee
name = "Ramu"
score = 30
if score>=40
console.log "Congratulations have passed the examination"
else
console.log "Sorry try again"
49
CoffeeScript
Open the command prompt and compile the .coffee file as shown below.
name = "Ramu";
score = 30;
}).call(this);
Now, open the command prompt again and run the CoffeeScript file as −
unless Statement
The unless statement is an additional feature provided by CoffeeScript. It is exactly opposite to
the if statement. The code in the unless block will be executed if the given condition is false.
Syntax
Given below is the syntax of the unless statement in CoffeeScript. Just like if statement, it
contains an unless keyword, a Boolean expression, and a block of code which will be executed
if the given expression is false.
unless expression
Statement(s) to be executed if the expression is false
50
CoffeeScript
Flow Diagram
Example
The following example demonstrates the usage of unless statement in CoffeeScript. Save this
code in a file with the name unless_example.coffee
name = "Ramu"
score = 30
unless score>=40
console.log "Sorry try again"
Open the command prompt and compile the .coffee file as shown below.
name = "Ramu";
score = 30;
51
CoffeeScript
}).call(this);
Now, open the command prompt again and run the CoffeeScript file as −
unless…else Statement
Just like the if else statement, we also have an unless else statement in CoffeeScript. It contains
a Boolean expression, an unless block, and an else block. If the given expression is false, the
unless block is executed and if it is true, the else block is executed.
Syntax
Given below is the syntax of the unless else statement in CoffeeScript.
unless expression
Statement(s) to be executed if the expression is false
else
Statement(s) to be executed if the expression is true
Flow Diagram
52
CoffeeScript
Example
The following example demonstrates the usage of unless-else statement in CoffeeScript. Save
this code in a file with the name unless_else_example.coffee
name = "Ramu"
score = 60
unless score>=40
console.log "Sorry try again"
else
console.log "Congratulations you have passed the exam"
Open the command prompt and compile the .coffee file as shown below.
name = "Ramu";
score = 60;
53
CoffeeScript
}).call(this);
Now, open the command prompt again and run the CoffeeScript file as shown below.
switch Statement
A switch statement allows a variable to be tested for equality against a list of values. Each value
is called a case, and the variable being switched on is checked for each switch case. Here is the
syntax of switch in JavaScript.
switch (expression){
case condition 1: statement(s)
break;
default: statement(s)
}
In JavaScript, after each switch case, we have to use the break statement. If we accidentally
forget the break statement, then there is a chance of falling from one switch case to other.
Each case statement have two clauses when and then. The when is followed by condition
and then is followed by the set of statements that are to be executed if that particular condition
54
CoffeeScript
is met. And finally, we have the optional else clause which holds the action for the default
condition.
Syntax
Given below is the syntax of the switch statement in CoffeeScript. We specify the expression
without parentheses and we separate the case statements by maintaining proper indentations.
switch expression
when condition1 then statements
when condition2 then statements
when condition3 then statements
else statements
Flow Diagram
Example
The following example demonstrates the usage of switch statement in CoffeeScript. Save this
code in a file with name switch_example.coffee
name="Ramu"
score=75
message = switch
when score>=75 then "Congrats your grade is A"
55
CoffeeScript
Open the command prompt and compile the .coffee file as shown below.
name = "Ramu";
score = 75;
message = (function() {
switch (false) {
case !(score >= 75):
return "Congrats your grade is A";
case !(score >= 60):
return "Your grade is B";
case !(score >= 50):
return "Your grade is C";
case !(score >= 35):
return "Your grade is D";
default:
return "Your grade is F and you are failed in the exam";
}
})();
console.log(message);
}).call(this);
56
CoffeeScript
Now, open the command prompt again and run the CoffeeScript file as −
Example
The following example shows how to write a CoffeeScript switch statement by specifying multiple
values for the when clause. Save this code in a file with name switch_multiple_example.coffee
name="Ramu"
score=75
message = switch name
when "Ramu","Mohammed" then "You have passed the examination with grade A"
when "John","Julia" then "You have passed the examination with grade is B"
when "Rajan" then "Sorry you failed in the examination"
else "No result"
console.log message
Open the command prompt and compile the .coffee file as shown below.
name = "Ramu";
score = 75;
message = (function() {
switch (name) {
case "Ramu":
57
CoffeeScript
case "Mohammed":
return "You have passed the examination with grade A";
case "John":
case "Julia":
return "You have passed the examination with grade is B";
case "Rajan":
return "Sorry you failed in the examination";
default:
return "No result";
}
})();
console.log(message);
}).call(this);
Now, open the command prompt again and run the CoffeeScript file as shown below.
Following are the statements in CoffeeScript that are written using then keyword.
if-then statement
Using the if-then statement we can write the if statement of CoffeeScript in a single
1 line. It consists of a Boolean expression followed by then keyword, which is followed by
one or more statements. These statements execute when the given Boolean expression
is true.
if-then...else statement
2 The if-then statement can be followed by an optional else statement, which executes
when the Boolean expression is false. Using if-then...else statement, we can write the
if...else statement in a single line.
58
CoffeeScript
unless-then statement
Using the unless-then statement, we can write the unless statement of CoffeeScript in
3 a single line. It consists of a Boolean expression followed by then keyword, which is
followed by one or more statements. These statements execute when the given Boolean
expression is false.
if…then Statement
Using the if-then statement, we can write the if statement of CoffeeScript in a single line. It
consists of a Boolean expression followed by then keyword, which is followed by one or more
statements. These statements execute when the given Boolean expression is true.
Syntax
Following is the syntax of the if-then statement in CoffeeScript.
Example
Given below is the example of the if-then statement of CoffeeScript. Save this code in a file with
name if_then_exmple.coffee
name = "Ramu"
score = 60
if score>40 then console.log "Congratulations you have passed the examination"
Open the command prompt and compile the .coffee file as shown below.
name = "Ramu";
score = 60;
59
CoffeeScript
}).call(this);
Now, open the Node.js command prompt again and run the CoffeeScript file as −
if…then…else Statement
Using the if-then...else statement, we can write the if statement of CoffeeScript in a single line.
It consists of a Boolean expression followed by then keyword, which is followed by one or more
statements. These statements execute when the given Boolean expression is true.
Syntax
Following is the syntax of the if-then statement in CoffeeScript.
Example
Given below is the example of the if-then statement of CoffeeScript. Save this code in a file with
name if_then_exmple.coffee
name = "Ramu"
score = 30
if score>=40 then console.log "Congratulations you have passed the examination" else
console.log "Sorry try again"
Open the command prompt and compile the .coffee file as shown below.
name = "Ramu";
60
CoffeeScript
score = 30;
}).call(this);
Now, open the Node.js command prompt again and run the CoffeeScript file as −
unless…then Statement
Using the unless..then statement, we can write the unless statement of CoffeeScript in a single
line. It consists of a Boolean expression followed by then keyword, which is followed by one or
more statements. These statements execute when the given Boolean expression is false.
Syntax
Following the syntax of the unless-then statement in CoffeeScript.
Example
Given below is the example of the unless-then statement of CoffeeScript. Save the following
example in a file with name unless_then_exmple.coffee
name = "Ramu"
score = 30
unless score>=40 then console.log "Sorry try again"
Open the command prompt and compile the .coffee file as shown below.
61
CoffeeScript
name = "Ramu";
score = 30;
}).call(this);
Now, open the command prompt again and run the CoffeeScript file as −
unless-then…else Statement
Using the unless-then statement, we can write the unless statement of CoffeeScript in a single
line. It consists of a Boolean expression followed by then keyword, which is followed by one or
more statements. These statements execute when the given Boolean expression is false.
Syntax
Following the syntax of the unless-then statement in CoffeeScript.
Example
Given below is the example of the unless-then statement of CoffeeScript. Save the following
example in a file with name unless_then_exmple.coffee
name = "Ramu"
62
CoffeeScript
score = 60
unless score>=40 then console.log "Sorry try again" else console.log "congratulations
you have passed the examination."
Open the command prompt and compile the .coffee file as shown below.
name = "Ramu";
score = 60;
}).call(this);
Now, open the command prompt again and run the CoffeeScript file as −
#Postfix if
Statements to be executed if expression
63
CoffeeScript
#Postfix unless
Statements to be executed unless expression
64
9. CoffeeScript – Loops CoffeeScript
While coding, you may encounter a situation where you need to execute a block of code over
and over again. In such situations, you can use loop statements.
In general, statements are executed sequentially: The first statement in a function is executed
first, followed by the second, and so on.
A loop statement allows us to execute a statement or group of statements multiple times. Given
below is the general form of a loop statement in most of the programming languages
JavaScript provides while, for and for..in loops. The loops in CoffeeScript are similar to those
in JavaScript.
while loop and its variants are the only loop constructs in CoffeeScript. Instead of the commonly
used for loop, CoffeeScript provides you Comprehensions which are discussed in detail in later
chapters.
Syntax
Following is the syntax of the while loop in CoffeeScript. Here, there is no need of the
parenthesis to specify the Boolean expression and we have to indent the body of the loop using
(consistent number of) whitespaces instead of wrapping it with curly braces.
65
CoffeeScript
while expression
statements to be executed
Example
The following example demonstrates the usage of while loop in CoffeeScript. Save this code in
a file with name while_loop_example.coffee
Open the command prompt and compile the .coffee file as shown below.
count = 0;
}).call(this);
66
CoffeeScript
Now, open the command prompt again and run the CoffeeScript file as shown below.
Starting Loop
Current Count : 0
Current Count : 1
Current Count : 2
Current Count : 3
Current Count : 4
Current Count : 5
Current Count : 6
Current Count : 7
Current Count : 8
Current Count : 9
Set the variable to different value and then try
Variants of while
The While loop in CoffeeScript have two variants namely the until variant and the loop variant.
2 The loop variant is equivalent to the while loop with true value (while true). The
statements in this loop will be executed repeatedly until we exit the loop using the
Break statement.
67
CoffeeScript
Syntax
Given below is the syntax of the until loop in CoffeeScript.
until expression
statements to be executed if the given condition Is false
Example
The following example demonstrates the usage of until loop in CoffeeScript. Save this code in a
file with name until_loop_example.coffee
Open the command prompt and compile the .coffee file as shown below.
On compiling, it gives you the following JavaScript. Here you can observe that the until loop is
converted into while not in the resultant JavaScript code.
count = 0;
68
CoffeeScript
}).call(this);
Now, open the command prompt again and run the Coffee Script file as shown below.
Starting Loop
Current Count : 0
Current Count : 1
Current Count : 2
Current Count : 3
Current Count : 4
Current Count : 5
Current Count : 6
Current Count : 7
Current Count : 8
Current Count : 9
Set the variable to different value and then try
Syntax
Given below is the syntax of the loop alternative of the while loop in CoffeeScript.
loop
statements to be executed repeatedly
condition to exit the loop
Example
The following example demonstrates the usage of until loop in CoffeeScript. Here we have used
the Math function random() to generate random numbers, and if the number generated is 3, we
are exiting the loop using break statement. Save this code in a file with
name until_loop_example.coffee
loop
num = Math.random()*8|0
console.log num
69
CoffeeScript
Open the command prompt and compile the .coffee file as shown below.
while (true) {
num = Math.random() * 8 | 0;
console.log(num);
if (num === 5) {
break;
}
}
}).call(this);
Now, open the command prompt again and run the Coffee Script file as shown below.
2
0
2
3
7
4
6
2
0
1
4
6
5
70
10. CoffeeScript – Comprehensions CoffeeScript
In the previous chapter, we have learnt various loops provided by CoffeeScript, while and its
variants. In addition to those, CoffeeScript provides additional loop structures known as
comprehensions.
These comprehensions replace the for loop in other programming languages, if we add the
optional guard clauses and the value of the current array index explicitly. Using comprehensions,
we can iterate arrays as well as objects and the comprehensions that iterate arrays are
expressions, and we can return them in a function or assign to a variable.
for..in comprehensions
1 The for..in comprehension is the basic form of comprehension in CoffeeScript using this
we can iterate the elements of a list or array.
for..of comprehensions
2 Just like Arrays CoffeeScriptScript provides a containers to store key-value pairs known
as objects. We can iterate objects using the for..of comprehensions provided by
CoffeeScript.
list comprehensions
3 The list comprehensions in CoffeeScript are used to map an array of objects to another
array.
for…in Comprehensions
The for..in comprehension is the basic form of comprehension in CoffeeScript. Using this, we
can iterate the elements of a list or array.
Syntax
Suppose we have an array of elements in CoffeeScript as ['element1', 'element2', 'element3'] then
you can iterate these elements using the for-in comprehension as shown below.
Example
The following example demonstrates the usage of for…in comprehension in CoffeeScript. Save
this code in a file with name for_in_comprehension.coffee
71
CoffeeScript
Open the Node.js command prompt and compile the .coffee file as shown below.
On compiling, it gives you the following JavaScript. Here you can observe that the
comprehension is converted into the for loop.
}).call(this);
Now, open the command prompt again and run the CoffeeScript file as shown below.
Ram
Mohammed
John
for…of Comprehensions
Just like Arrays, CoffeeScript provides containers to store key-value pairs known as objects.
We can iterate objects using the for..of comprehensions provided by CoffeeScript.
Syntax
Suppose we have an object in CoffeeScript as { key1: value, key2: value, key3: value} then you can
iterate these elements using the for..of comprehension as shown below.
Example
The following example demonstrates the usage of the for..of comprehension provided by
CoffeeScript. Save this code in a file with name for_of_example.coffee
72
CoffeeScript
Open the command prompt and compile the .coffee file as shown below.
ref = {
name: "Mohammed",
age: 24,
phone: 9848022338
};
for (key in ref) {
value = ref[key];
console.log(key + "::" + value);
}
}).call(this);
Now, open the command prompt again and run the CoffeeScript file as shown below.
name::Mohammed
age::24
phone::9848022338
Note − We will discuss arrays, objects, and ranges in detail in individual chapters later in this
tutorial.
list Comprehensions
In CoffeeScript, we can also store a group of objects in an array. The list comprehensions are
used to map an array of objects to another array.
73
CoffeeScript
Syntax
Suppose we have an array of objects in CoffeeScript as [{key1: "value", key2: value}, {key1: "value",
key2: value}] then you can iterate these elements using the list comprehension as shown below.
for key,value of [ {key1: "value", key2: value}, {key1: "value", key2: value} ]
console.log key+"::"+value
Example
The following example demonstrates the usage of the list comprehension provided by
CoffeeScript. Save this code in a file with namelist_comprehensions.coffee
students =[
name: "Mohammed"
age: 24
phone: 9848022338
,
name: "Ram"
age: 25
phone: 9800000000
,
name: "Ram"
age: 25
phone: 9800000000
]
Open the command prompt and compile the .coffee file as shown below.
students = [
{
74
CoffeeScript
name: "Mohammed",
age: 24,
phone: 9848022338
}, {
name: "Ram",
age: 25,
phone: 9800000000
}, {
name: "Ram",
age: 25,
phone: 9800000000
}
];
names = (function() {
var i, len, results;
results = [];
for (i = 0, len = students.length; i < len; i++) {
student = students[i];
results.push(student.name);
}
return results;
})();
console.log(names);
}).call(this);
Now, open the command prompt again and run the CoffeeScript file as shown below.
c:\> list_comprehensions.coffee
75
CoffeeScript
Index of comprehensions
The list/array of elements have an index which can be used in comprehensions. You can use it
in comprehensions using a variable as shown below.
Example
The following example demonstrates the usage of index of the for…in comprehension in
CoffeeScript. Save this code in a file with name for_in_index.coffee
Open the command prompt and compile the .coffee file as shown below.
Now, open the command prompt again and run the CoffeeScript file as shown below.
76
CoffeeScript
Example
#Postfix for..in comprehension
console.log student for student in ['Ram', 'Mohammed', 'John'
Open the command prompt and compile the .coffee file as shown below.
}).call(this);
Now, open the command prompt again and run the CoffeeScript file as shown below.
Ram
Mohammed
John
Open the command prompt and compile the .coffee file as shown below.
ref = {
name: "Mohammed",
age: 24,
phone: 9848022338
};
for (key in ref) {
value = ref[key];
console.log(key + "::" + value);
}
}).call(this);
Now, open the command prompt again and run the CoffeeScript file as shown below.
78
CoffeeScript
name::Mohammed
age::24
phone::9848022338
Assigning to a variable
The comprehension we use to iterate arrays can be assigned to a variable and also returned by
a function.
Example
Consider the example given below. Here you can observe that we have retrieved the elements
of an array using for..in comprehension and assigned this to a variable named names. And we
also have a function which returns a comprehension explicitly using the return keyword. Save
this code in a file with name example.coffee
my_function =->
student = ['Ram', 'Mohammed', 'John']
Open the command prompt and compile the .coffee file as shown below.
my_function = function() {
var i, len, names, student, x;
student = ['Ram', 'Mohammed', 'John'];
79
CoffeeScript
names = (function() {
var i, len, results;
results = [];
for (i = 0, len = student.length; i < len; i++) {
x = student[i];
results.push(x);
}
return results;
})();
console.log("The contents of the variable names are ::" + names);
for (i = 0, len = student.length; i < len; i++) {
x = student[i];
return x;
}
};
}).call(this);
Now, open the command prompt again and run the CoffeeScript file as shown below.
The by keyword
CoffeeScript provides ranges to define a list of elements. For example, the range [1..10] is
equivalent to [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] where, every element is incremented by 1. We can
also change this increment using the by keyword of comprehensions.
Example
The following example demonstrates the usage of the by keyword of the for..in comprehension
provided by CoffeeScript. Save this code in a file with nameby_keyword_example.coffee
80
CoffeeScript
Open the command prompt and compile the .coffee file as shown below.
array = (function() {
var i, results;
results = [];
for (num = i = 1; i <= 10; num = i += 2) {
results.push(num);
}
return results;
})();
console.log(array);
}).call(this);
Now, open the command prompt again and run the CoffeeScript file as shown below.
[ 1, 3, 5, 7, 9 ]
81
11. CoffeeScript – Functions CoffeeScript
A function is a block of reusable code that can be called anywhere in your program. This
eliminates the need of writing the same code again and again. It helps programmers in writing
modular codes.
Functions allow a programmer to divide a big program into a number of small and manageable
functions.
In general, using JavaScript, we can define two types of functions – named functions, the
regular functions with function name body and, Function expressions. Using function
expressions, we can assign functions to variables.
//named function
function sayHello(){
return("Hello there");
}
//function expressions
var message = function sayHello(){
return("Hello there");
}
Functions in CoffeeScript
The syntax of function in CoffeeScript is simpler as compared to JavaScript. In CoffeeScript, we
define only function expressions.
The function keyword is eliminated in CoffeeScript. To define a function here, we have to use a
thin arrow (->).
Behind the scenes, the CoffeeScript compiler converts the arrow in to the function definition in
JavaScript. (function() {});)
It is not mandatory to use the return keyword in CoffeeScript. Every function in CoffeeScript
returns the last statement in the function automatically.
If we want to return to the calling function or return a value before we reach the end of
the function, then we can use the return keyword.
In addition to in-line functions (functions that are in single line), we can also define multi-
line functions in CoffeeScript. Since the curly braces are eliminated, we can do it by
maintaining proper indentations.
82
CoffeeScript
Defining a Function
Following is the syntax of defining a function in CoffeeScript.
Example
Given below is an example of a function in CoffeeScript. In here, we have created a function
named greet. This function automatically returns the statement in it. Save it in a file with the
name function_example.coffee
c:\>coffee -c function_example.coffee
On compiling, it generates the following JavaScript code. Here you can observe that the
CoffeeScript compiler automatically returned the string value in the function named greet().
greet = greet() {
return "This is an example of a function";
};
}).call(this);
Multi-line Functions
We can also define a function with multiple lines by maintaining indentations instead of curly
braces. But we have to be consistent with the indentation we follow for a line throughout a
function.
greet = ->
console.log "How hello how are you"
On compiling, the above CoffeeScript gives you the following JavaScript code. The CoffeeScript
compiler grabs the body of the function that we have separated using indentations and placed
within the curly braces.
greet = function() {
return console.log("Sum of the two numbers is " + c);
};
}).call(this);
On compiling the above CoffeeScript file, it will generate the following JavaScript.
my_function = function() {
return "This is an example of a function";
};
}).call(this);
Invoking a Function
After defining a function, we need to invoke that function. You can simply invoke a function by
placing parenthesis after its name as shown in the following example.
add = ->
a=20;b=30
c=a+b
console.log "Sum of the two numbers is: "+c
add()
add = function() {
var a, b, c;
a = 20;
b = 30;
c = a + b;
return console.log("Sum of the two numbers is: " + c);
};
add();
}).call(this);
my_function argument_1,argument_2
or
my_function (argument_1,argument_2)
Note − While invoking a function by passing arguments to it, the usage of parenthesis is
optional.
In the following example, we have created a function named add() that accepts two parameters
and we have invoked it.
85
CoffeeScript
add = function(a, b) {
var c;
c = a + b;
return console.log("Sum of the two numbers is: " + c);
};
add(10, 20);
}).call(this);
Default Arguments
CoffeeScript supports default arguments too. We can assign default values to the arguments of
a function, as shown in the following example.
add = function(a, b) {
var c;
if (a == null) {
86
CoffeeScript
a = 1;
}
if (b == null) {
b = 2;
}
c = a + b;
return console.log("Sum of the two numbers is: " + c);
};
add(10, 20);
add()
}).call(this);
87
CoffeeScript
88
12. CoffeeScript – Strings CoffeeScript
The String object lets you work with a series of characters. As in most of the programming
languages, the Strings in CoffeeScript are declared using quotes as −
console.log(my_string);
}).call(this);
String Concatenation
We can concatenate two strings using the "+" symbol as shown below.
new_string = "Hello how are you " + " Welcome to Tutorials point";
console.log(new_String);
}).call(this);
89
CoffeeScript
If you execute the above example, you can observe the concatenated String as shown below.
String Interpolation
CoffeeScript also provides a feature known as String interpolation to include variables in
stings. This feature of CoffeeScript was inspired from Ruby language.
String interpolation was done using the double quotes "", a hash tag # and a pair of curly
braces { }. The String is declared in curly braces and the variable that is to be interpolated is
wrapped within the curly braces which are prefixed by a hash tag as shown below.
name = "Raju"
age = 26
message ="Hello #{name} your age is #{age}"
console.log message
On compiling the above example, it generates the following JavaScript. Here you can observe
the String interpolation is converted into normal concatenation using the + symbol.
name = "Raju";
age = 26;
console.log(message);
}).call(this);
If you execute the above CoffeeScript code, it gives you the following output.
The variable that is passed as #{variable} is interpolated only if the string is enclosed between
double quotes " ". Using single quotes ' ' instead of double quotes produces the line as it is
without interpolation. Consider the following example.
name = "Raju"
age = 26
90
CoffeeScript
If we use single quotes instead of double quotes in interpolation, you will get the following
output.
CoffeeScript allows multiple lines in Strings without concatenating them as shown below.
hello how are you Welcome to tutorials point Have a nice day.
Since we can use JavaScript libraries in our CoffeeScript code, we can use all those methods in
our CoffeeScript programs.
String Methods
Following is the list of methods of the String object of JavaScript. Click on the name of these
methods to get an example demonstrating their usage in CoffeeScript.
Method Description
charCodeAt() Returns a number indicating the Unicode value of the character at the
given index.
concat() Combines the text of two strings and returns a new string.
indexOf() Returns the index within the calling String object of the first occurrence
of the specified value, or -1 if not found.
lastIndexOf() Returns the index within the calling String object of the last occurrence
of the specified value, or -1 if not found.
91
CoffeeScript
search() Executes the search for a match between a regular expression and a
specified string.
split() Splits a String object into an array of strings by separating the string
into substrings.
substring() Returns the characters in a string between two indexes into the string.
toLocaleLowerCase() The characters within a string are converted to lower case while
respecting the current locale.
toLocaleUpperCase() The characters within a string are converted to upper case while
respecting the current locale.
charAt method
Description
The charAt() method of JavaScript returns the character of the current string that exists in the
specified index.
Characters in a string are indexed from left to right. The index of the first character is 0, and the
index of the last character is one less than the length of the string. (stringName_length − 1 )
Syntax
Given below is the syntax of charAt() method of JavaScript. We can use the same method from
the CoffeeScript code.
string.charAt(index);
It accepts an integer value representing the index of the String and returns the character at the
specified index.
Example
The following example demonstrates the usage of charAt() method of JavaScript in CoffeeScript
code. Save this code in a file with name string_charat.coffee
92
CoffeeScript
Open the command prompt and compile the .coffee file as shown below.
}).call(this);
Now, open the command prompt again and run the CoffeeScript file as shown below.
93
CoffeeScript
charCodeAt Method
Description
This method returns a number indicating the Unicode value of the character at the given index.
Unicode code points range from 0 to 1,114,111. The first 128 Unicode code points are a direct
match of the ASCII character encoding. charCodeAt() always returns a value that is less than
65,536.
Syntax
Given below is the syntax of charCodeAt() method of JavaScript. We can use the same method
from the CoffeeScript code.
string. charCodeAt(index)
It accepts an integer value representing the index of the String and returns the Unicode value
of the character existing at the specified index of the String. It returns NaN if the given index is
not between 0 and 1 less than the length of the string.
Example
The following example demonstrates the usage of charCodeAt() method of JavaScript in
CoffeeScript code. Save this code in a file with name string_charcodeat.coffee
console.log "The Unicode of the character at the index (0) is:" + str.charCodeAt 0
console.log "The Unicode of the character at the index (1) is:" + str.charCodeAt 1
console.log "The Unicode of the character at the index (2) is:" + str.charCodeAt 2
console.log "The Unicode of the character at the index (3) is:" + str.charCodeAt 3
console.log "The Unicode of the character at the index (4) is:" + str.charCodeAt 4
console.log "The Unicode of the character at the index (5) is:" + str.charCodeAt 5
Open the command prompt and compile the .coffee file as shown below.
94
CoffeeScript
}).call(this);
Now, open the command prompt again and run the CoffeeScript file as shown below.
concat() Method
Description
This method adds two or more strings and returns the resultant string.
Syntax
Given below is the syntax of concat() method of JavaScript. We can use the same method from
the CoffeeScript code.
95
CoffeeScript
Example
The following example demonstrates the usage of concat() method of JavaScript in CoffeeScript
code. Save this code in a file with the name string_concat.coffee
Open the command prompt and compile the .coffee file as shown below.
str3 = str1.concat(str2);
}).call(this);
Now, open the command prompt again and run the CoffeeScript file as shown below.
96
CoffeeScript
indexOf() Method
Description
This method accepts a sub string and returns the index of its first occurrence within the calling
String object. It also accepts an optional parameter fromIndex which will be the starting point of
the search. This method returns −1 if the value is not found.
Syntax
Given below is the syntax of indexOf() method of JavaScript. We can use the same method from
the CoffeeScript code.
string.indexOf(searchValue[, fromIndex])
Example
The following example demonstrates the usage of indexOf() method of JavaScript in CoffeeScript
code. Save this code in a file with name string_indexof.coffee
Open the command prompt and compile the .coffee file as shown below.
index = str1.indexOf("string");
index = str1.indexOf("one");
97
CoffeeScript
}).call(this);
Now, open the command prompt again and run the CoffeeScript file as shown below.
lastIndexOf() Method
Description
This method accepts a sub string and returns the index of its last occurrence within the calling
String object. It also accepts an optional parameter fromIndex to start the search from, it
returns -1 if the value is not found.
Syntax
Given below is the syntax of lastIndexOf() method of JavaScript. We can use the same method
from the CoffeeScript code.
string.lastIndexOf(searchValue[, fromIndex])
Example
The following example demonstrates the usage of lastIndexOf() method of JavaScript in
CoffeeScript code. Save this code in a file with name string_lastindexof.coffee
str1 = "A sentence does not end with because because, because is a conjunction."
index = str1.lastIndexOf "because"
console.log "lastIndexOf the given string because is :" + index
Open the command prompt and compile the .coffee file as shown below.
98
CoffeeScript
str1 = "A sentence does not end with because, because because is a conjunction.";
index = str1.lastIndexOf("because");
index = str1.lastIndexOf("a");
}).call(this);
Now, open the command prompt again and run the CoffeeScript file as shown below.
localeCompare() Method
Description
This method accepts a string and compares it with the calling String object. If both are equal, it
returns 0; else it returns -1 or 1. And if the string passed as parameter comes first in the sorted
order according to local browser language, it returns 1; and if the calling string comes first in
the sorted order, -1 is returned.
Syntax
Given below is the syntax of localeCompare() method of JavaScript. We can use the same
method from the CoffeeScript code.
string.localeCompare( param )
Example
99
CoffeeScript
100
CoffeeScript
Open the command prompt and compile the .coffee file as shown below.
str3 = "abcd";
str4 = "xyz";
index = str1.localeCompare(str2);
switch (index) {
case 0:
console.log("Both strings are equal");
break;
case 1:
console.log("Both strings are not equal and the string passed as parameter will
be first in the sorted order.");
break;
case -1:
console.log("Both strings are not equal and the calling string object will be
first in the sorted order.");
101
CoffeeScript
index = str1.localeCompare(str3);
switch (index) {
case 0:
console.log("Both strings are equal");
break;
case 1:
console.log("Both strings are not equal and the string passed as parameter will
be first in the sorted order.");
break;
case -1:
console.log("Both strings are not equal and the calling string object will be
first in the sorted order.");
}
index = str1.localeCompare(str4);
index = str1.localeCompare(str3);
switch (index) {
case 0:
console.log("Both strings are equal");
break;
case 1:
console.log("Both strings are not equal and the string passed as parameter will
be first in the sorted order.");
break;
case -1:
console.log("Both strings are not equal and the calling string object will be
first in the sorted order.");
}
102
CoffeeScript
}).call(this);
Now, open the command prompt again and run the CoffeeScript file as shown below.
match() Method
Description
This method is used to retrieve the matches when matching a string against a regular expression.
It works similar to regexp.exec(string) without the g flag and it returns an array with all matches
with the g flag.
Syntax
Given below is the syntax of match() method of JavaScript. We can use the same method in the
CoffeeScript code.
string.match( param )
Example
The following example demonstrates the usage of match() method of JavaScript in CoffeeScript
code. Save this code in a file with name string_localecompare.coffee
103
CoffeeScript
console.log found
Open the command prompt and compile the .coffee file as shown below.
re = /(chapter \d+(\.\d)*)/i;
found = str.match(re);
console.log(found);
}).call(this);
Now, open the command prompt again and run the CoffeeScript file as shown below.
[ 'Chapter 3.4.5.1',
'Chapter 3.4.5.1',
'.1',
index: 26,
input: 'For more information, see Chapter 3.4.5.1' ]
search() Method
Description
104
CoffeeScript
This method accepts a regular expression in the form of object and searches the calling string
for the given regular expression. If a match occurs, it returns the index of the regular expression
inside the string and if it doesn't, it returns the value -1.
Syntax
Given below is the syntax of search() method of JavaScript. We can use the same method in the
CoffeeScript code.
string.search(regexp)
Example
The following example demonstrates the usage of search() method of JavaScript in CoffeeScript
code. Save this code in a file with name string_search.coffee
regex = /apples/gi
string = "Apples are round, and apples are juicy."
if string.search(regex) == -1
console.log "Does not contain Apples"
else
console.log "Contains Apples"
Open the command prompt and compile the .coffee file as shown below.
regex = /apples/gi;
105
CoffeeScript
}).call(this);
Now, open the command prompt again and run the CoffeeScript file as shown below.
Contains Apples
slice() Method
Description
This method accepts begin and end index values, and returns the portion of the calling string
object that exists between the given index values. If we doesn't pass the end index value it takes
the end of the string as the end index value.
Syntax
Given below is the syntax of slice() method of JavaScript. We can use the same method in the
CoffeeScript code.
Example
The following example demonstrates the usage of slice() method of JavaScript in CoffeeScript
code. Save this code in a file with name string_slice.coffee
Open the command prompt and compile the .coffee file as shown below.
}).call(this);
Now, open the command prompt again and run the CoffeeScript file as shown below.
The required slice of the string is :: les are round, and apples are juic
split() Method
Description
This method is used to split a string in to small parts. It accepts a special character and an
integer. The character acts as a separator and indicates where to split the string and the integer
indicates into how many parts the string is to be divided. If we do not pass a separator, the
whole string is returned.
Syntax
Given below is the syntax of split() method of JavaScript. We can use the same method in the
CoffeeScript code.
string.split([separator][, limit])
Example
The following example demonstrates the usage of split() method of JavaScript in CoffeeScript
code. Save this code in a file with name string_split.coffee
console.log "The two resultant strings of the split operation are :: "
console.log my_string
Open the command prompt and compile the .coffee file as shown below.
console.log(my_string);
}).call(this);
Now, open the command prompt again and run the CoffeeScript file as shown below.
substr() Method
Description
This method is used to return a required substring of a string. It accepts an integer value
indicating the starting value of the substring and the length of the string and returns the required
substring. If the start value is negative, then substr() method uses it as a character index from
the end of the string.
Syntax
Given below is the syntax of substr() method of JavaScript. We can use the same method in the
CoffeeScript code.
string.substr(start[, length])
Example
The following example demonstrates the usage of substr() method of JavaScript in CoffeeScript
code. Save this code in a file with name string_substr.coffee
console.log "The sub string having start and length as (1,2) is : " + str.substr 1,2
console.log "The sub string having start and length as (-2,2) is : " + str.substr -
2,2
console.log "The sub string having start and length as (1) is : " + str.substr 1
console.log "The sub string having start and length as (-20, 2) is : " + str.substr -
20,2
console.log "The sub string having start and length as (20, 2) is : " + str.substr
20,2;
Open the command prompt and compile the .coffee file as shown below.
console.log("The sub string having start and length as (1,2) is : " + str.substr(1,
2));
console.log("The sub string having start and length as (-2,2) is : " + str.substr(-
2, 2));
console.log("The sub string having start and length as (1) is : " + str.substr(1));
}).call(this);
Now, open the command prompt again and run the CoffeeScript file as shown below.
toLocaleLowerCase() method
Description
This method is used to convert the characters within a string to lower case while respecting the
current locale. For most languages, it returns the same output as toLowerCase.
Syntax
Given below is the syntax of toLocaleLowerCase( ) method of JavaScript. We can use the same
method in the CoffeeScript code.
string.toLocaleLowerCase( )
Example
The following example demonstrates the usage of toLocaleLowerCase( ) method of JavaScript in
CoffeeScript code. Save this code in a file with nametoLocaleLowerCase.coffee
Open the command prompt and compile the .coffee file as shown below.
console.log(str.toLocaleLowerCase());
}).call(this);
110
CoffeeScript
Now, open the command prompt again and run the CoffeeScript file as shown below.
toLocaleUpperCase() method
Description
This method is used to convert the characters within a string to uppercase while respecting the
current locale. For most languages, it returns the same output as toUpperCase.
Syntax
Given below is the syntax of toLocaleUpperCase( ) method of JavaScript. We can use the same
method in the CoffeeScript code.
string.toLocaleUpperCase( )
Example
The following example demonstrates the usage of toLocaleUpperCase( ) method of JavaScript in
CoffeeScript code. Save this code in a file with nametoLocaleUpperCase.coffee
Open the command prompt and compile the .coffee file as shown below.
console.log(str.toLocaleUpperCase());
}).call(this);
Now, open the command prompt again and run the CoffeeScript file as shown below.
111
CoffeeScript
toLowerCase() method
Description
This method returns the calling string value converted to lowercase.
Syntax
Given below is the syntax of toLowerCase( ) method of JavaScript. We can use the same method
in the CoffeeScript code.
string.toLowerCase( )
Example
The following example demonstrates the usage of toLowerCase( ) method of JavaScript in
CoffeeScript code. Save this code in a file with name tolowercase.coffee
console.log(str.toLowerCase());
}).call(this);
Open the command prompt and compile the .coffee file as shown below.
console.log(str.toLowerCase());
}).call(this);
Now, open the command prompt again and run the CoffeeScript file as shown below.
toUpperCase() method
Description
This method returns the calling string value converted to Uppercase.
Syntax
Given below is the syntax of toUpperCase( ) method of JavaScript. We can use the same method
in the CoffeeScript code.
string.toUpperCase( )
Example
The following example demonstrates the usage of toUpperCase( ) method of JavaScript in
CoffeeScript code. Save this code in a file with name touppercase.coffee
Open the command prompt and compile the .coffee file as shown below.
113
CoffeeScript
console.log(str.toUpperCase());
}).call(this);
Now, open the command prompt again and run the CoffeeScript file as shown below.
114
13. CoffeeScript – Arrays CoffeeScript
The Array object lets you store multiple values in a single variable. It stores a fixed-size
sequential collection of elements of the same type. An array is used to store a collection of data,
but it is often more useful to think of an array as a collection of variables of the same type.
Syntax
To create an array, we have to instantiate it using the new operator as shown below.
The Array() constructor accepts the list of string or integer types. We can also specify the length
of the array by passing a single integer to its constructor.
We can also define an array by simply providing the list of its elements in the square braces ( [ ])
as shown below.
Example
Following is an example of defining an array in CoffeeScript. Save this code in a file with
name array_example.coffee
student = ["Rahman","Ramu","Ravi","Robert"]
Open the command prompt and compile the .coffee file as shown below.
}).call(this);
115
CoffeeScript
student = [
"Rahman"
"Ramu"
"Ravi"
"Robert"
]
Example
The following example demonstrates the retrieval of elements of an array using comprehensions.
Save this code in a file with name array_comprehensions.coffee
Open the command prompt and compile the .coffee file as shown below.
}).call(this);
Now, open the command prompt again and run the CoffeeScript file as shown below.
116
CoffeeScript
Rahman
Ramu
Ravi
Robert
Unlike the Arrays in other programming languages the arrays in CoffeeScript can have multiple
types of data i.e. both string and numericals.
Example
Here is an example of a CoffeeScript array holding multiple types of data.
117
14. CoffeeScript – Objects CoffeeScript
Objects in CoffeeScript are similar to those in JavaScript. These are a collection of the properties,
where a property includes a key and a value separated by a semi colon (:). In short, CoffeeScript
objects are a collection of key-value pairs. The objects are defined using curly braces, an empty
object is represented as {}.
Syntax
Given below is the syntax of an object in CoffeeScript. In here, we place the key-value pairs of
the objects within the curly braces and they are separated using comma ( ,).
Example
Following is an example of defining an object in CoffeeScript. Save this code in a file with
name objects_example.coffee
Open the command prompt and compile the .coffee file as shown below.
student = {
name: "Mohammed",
age: 24,
phone: 9848022338
};
}).call(this);
Just as in arrays, we can remove the commas by specifying the key-value pairs in new lines as
shown below.
student = {
name: "Mohammed"
118
CoffeeScript
age: 24
phone: 9848022338
}
Example
We can rewrite the above example without curly braces as shown below.
student =
name: "Mohammed"
age: 24
phone: 9848022338
Nested objects
In CoffeeScript, we can write objects within objects.
Example
The following example demonstrates the nested objects in CoffeeScript. Save this code in a file
with name nested_objects.coffee
contact =
personal:
email: "[email protected]"
phone: 9848022338
professional:
email: "[email protected]"
phone: 9848033228
Open the command prompt and compile the .coffee file as shown below.
119
CoffeeScript
contact = {
personal: {
email: "[email protected]",
phone: 9848022338
},
professional: {
email: "[email protected]",
phone: 9848033228
}
};
}).call(this);
Example
The following is an example showing how to iterate the contents of an object using
comprehensions. Save this code in a file with name object_comprehensions.coffee
student =
name: "Mohammed"
age: 24
phone: 9848022338
Open the command prompt and compile the .coffee file as shown below.
120
CoffeeScript
student = {
name: "Mohammed",
age: 24,
phone: 9848022338
};
}).call(this);
Now, open the command prompt again and run the CoffeeScript file as shown below.
name::Mohammed
age::24
phone::9848022338
Arrays of Objects
In CoffeeScript, an array can also contain objects in as shown below.
a = [
object1_key1: value
object1_key2: value
object1_key3: value
,
object2_key1: value
object2_key2: value
object2_key3: value
]
The following example shows how to define an array of objects. We can just list the key value
pairs of the objects we want in an array by separating them using commas (,).
121
CoffeeScript
students =[
name: "Mohammed"
age: 24
phone: 9848022338
,
name: "Ram"
age: 25
phone: 9800000000
,
name: "Ram"
age: 25
phone: 9800000000
]
console.log student for student in students
Open the command prompt and compile the .coffee file as shown below.
students = [
{
name: "Mohammed",
age: 24,
phone: 9848022338
}, {
name: "Ram",
age: 25,
phone: 9800000000
}, {
name: "Ram",
age: 25,
phone: 9800000000
}
122
CoffeeScript
];
}).call(this);
Now, open the command prompt again and run the CoffeeScript file as shown below.
Reserved Keywords
JavaScript does not allow reserved keywords as property names of an object, if we want use
them, we have to wrap them using double quotes " "
Example
Consider the following example. Here we have created a property with name class, which is a
reserved keyword. Save this code in a file with name reserved_keywords.coffee
student ={
name: "Mohammed"
age: 24
phone: 9848022338
class: "X"
}
console.log key+"::"+value for key,value of student
Open the command prompt and compile the .coffee file as shown below.
On compiling, it gives you the following JavaScript. Here you can observe that the CoffeeScript
compiler wrapped the keyword class with double quotes on behalf of us.
(function() {
var key, student, value;
student = {
name: "Mohammed",
age: 24,
phone: 9848022338,
"class": "X"
};
}).call(this);
Now, open the command prompt again and run the CoffeeScript file as shown below.
name::Mohammed
age::24
phone::9848022338
class::X
124
15. CoffeeScript – Ranges CoffeeScript
In the previous chapter, we have seen Arrays in CoffeeScript, while programming we will face
some scenarios where we have to store a sequence of numerical values in an array as shown
below.
numbers =[1,2,3,4,5,6,7,8,9,10]
CoffeeScript provides a shorter way of expressing the arrays containing a sequence of numerical
values, known as ranges. This feature of CoffeeScript is inspired from Ruby.
Syntax
Ranges are created by two numerical values, the first and last positions in the range, separated
by .. or .... With two dots (1..4), the range is inclusive (1, 2, 3, 4); with three dots (1...4), the
range excludes the end (1, 2, 3).
Given below is the syntax of ranges in CoffeeScript. We will define the values in a range between
square braces [ ] just like arrays. In ranges, while storing a sequence of numerical values, instead
of providing the values of the whole sequence, we can just specify its begin and end values
separated by two dots (..) as shown below.
range =[Begin..End]
Example
Here is an example of ranges in CoffeeScript. Save this in a file with name
ranges_example.coffee.
numbers =[0..9]
console.log "The contents of the range are: "+ numbers
Open the command prompt and compile the .coffee file as shown below.
On compiling, it gives you the following JavaScript. Here you can observe that the range is
converted in to complete CoffeeScript array.
125
CoffeeScript
}).call(this);
Now, open the command prompt again and run the CoffeeScript file as shown below.
range =[Begin...End]
Example
We can rewrite the above example by excluding the end value as shown below. Save the
following contents in a file with name range_excluding_end.coffee
numbers =[0...9]
console.log "The contents of the range are:: "+ numbers
Open the command prompt and compile the .coffee file as shown below.
}).call(this);
Now, open the command prompt again and run the CoffeeScript file as shown below.
126
CoffeeScript
On executing, the CoffeeScript file produces the following output. In here, you can observe that
the end value 9 is excluded.
Example
Consider the following example. Here we have defined a range using variables. Save this code
in a file with name range_variables.coffee
start=0
end=9
numbers =[start..end]
console.log "The contents of the range are: "+ numbers
Open the command prompt and compile the .coffee file as shown below.
start = 0;
end = 9;
numbers = (function() {
results = [];
for (var i = start; start <= end ? i <= end : i >= end; start <= end ? i++ : i-
-){ results.push(i); }
return results;
}).apply(this);
}).call(this);
127
CoffeeScript
Now, open the command prompt again and run the CoffeeScript file as shown below.
On executing, the CoffeeScript file produces the following output. In here, you can observe that
the end value 9 is excluded.
Assume that we have an array having numerical values, say 0 to 9, then we can retrieve the
first 4 elements of it as shown below.
num = [1, 2, 3, 4, 5, 6, 7, 8, 9]
data = num[0..5]
Negative values represent the elements from the end, for example, -1 indicates 9. If we specify
a negative number 3 followed by two dots, the last three elements of the array will be extracted.
data = num[-3..]
If we specify only two dots in the range of an array as num[..], then the complete array will be
extracted. We can also replace an array segment with other elements using ranges as shown
below.
num[2..6] = [13,14,15,16,17]
Example
The following example demonstrates the use of ranges with arrays. Save this code in a file with
name range_arrays.coffee
128
CoffeeScript
Open the command prompt and compile the .coffee file as shown below.
On compiling, it gives you the following JavaScript. Here you can observe that all the ranges are
converted in to the slice() method calls of JavaScript.
data = num.slice(-3);
}).call(this);
Now, open the command prompt again and run the CoffeeScript file as shown below.
129
CoffeeScript
On executing, the CoffeeScript file produces the following output. In here, you can observe that
the end value 9 is excluded.
Example
The following example demonstrates the use of ranges with Strings. Here we have created a
string and extracted a substring from it using ranges. Save this code in a file with name
ranges_with_strings.coffee
Open the command prompt and compile the .coffee file as shown below.
console.log(new_string);
}).call(this);
Now, open the command prompt again and run the CoffeeScript file as shown below.
130
CoffeeScript
On executing, the CoffeeScript file produces the following output. In here, you can observe that
the end value 9 is excluded.
Welcome to
Example
Following is an example of using comprehensions over ranges. Here we have created a range
and retrieved the elements in it using comprehensions. Save this code in a file with the
name comprehensions_over_ranges.coffee
numbers =[0..9]
console.log "The elements of the range are: "
console.log num for num in numbers
Open the command prompt and compile the .coffee file as shown below.
}).call(this);
Now, open the command prompt again and run the CoffeeScript file as shown below.
131
CoffeeScript
On executing, the CoffeeScript file produces the following output. In here, you can observe that
the end value 9 is excluded.
In the same way We can also change this increment using the by keyword of comprehensions.
132
16. CoffeeScript – Splat CoffeeScript
In the previous chapters, we have seen how to define a function and invoke a function and pass
arguments to it. In general, we can pass a fixed number of arguments to a function. While
programming, we may face situations where we need to pass variable arguments to these
functions. In JavaScript, we use objects to accept variable number of arguments to a function.
CoffeeScript provides a feature called splats to pass multiple arguments to functions. We use
splats in functions by placing three dots after the argument name and, it is denoted by ...
Syntax
Given below is the syntax of accepting multiple arguments within a function using splats.
my_function = (arguments...)->
............
............
............
Example
Following is an example of accepting multiple arguments within a function, using splats. Here
we have defined a function named indian_team() using splats. We are calling this function thrice
and we are passing 4 players, 6 players, and full squad simultaneously, each time we call it.
Since we have used splats in the function definition, it accepts variable number of arguments
each time we call it. Save this code in a file with namesplats_definition.coffee
#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"
133
CoffeeScript
Open the command prompt and compile the .coffee file as shown below.
indian_team = function() {
var Captain, WiseCaptain, first, others, second, team;
first = arguments[0], second = arguments[1], others = 3 <= arguments.length ?
slice.call(arguments, 2) : [];
Captain = first;
WiseCaptain = second;
team = others;
console.log("Captain: " + Captain);
console.log("Wise captain: " + WiseCaptain);
return console.log("Other team members: " + team);
};
134
CoffeeScript
}).call(this);
Now, open the command prompt again and run the CoffeeScript file as shown below.
my_function values...
Example
135
CoffeeScript
Following is an example of calling a function using splats. Save this code in a file with
namesplats_call.coffee
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"
]
indian_team squad...
Open the command prompt and compile the .coffee file as shown below.
136
CoffeeScript
indian_team = function() {
var Captain, WiseCaptain, first, others, second, team;
first = arguments[0], second = arguments[1], others = 3 <= arguments.length ?
slice.call(arguments, 2) : [];
Captain = first;
WiseCaptain = second;
team = others;
console.log("Captain: " + Captain);
console.log("Wise captain: " + WiseCaptain);
return 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"];
indian_team.apply(null, squad);
}).call(this);
Now, open the command prompt again and run the CoffeeScript file as shown below.
137
CoffeeScript
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"
]
indian_team squad...
138
CoffeeScript
Open the command prompt and compile the .coffee file as shown below.
indian_team = function() {
var Captain, Wicketkeeper, WiseCaptain, first, i, last, others, second, team;
first = arguments[0], second = arguments[1], others = 4 <= arguments.length ?
slice.call(arguments, 2, i = arguments.length - 1) : (i = 2, []), last =
arguments[i++];
Captain = first;
WiseCaptain = second;
team = others;
Wicketkeeper = last;
console.log("Captain: " + Captain);
console.log("Wise captain: " + WiseCaptain);
console.log("Wicket keeper is:" + last);
return 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"];
indian_team.apply(null, squad);
}).call(this);
Now, open the command prompt again and run the CoffeeScript file as shown below.
139
CoffeeScript
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"
140
CoffeeScript
indian_team squad...
Open the command prompt and compile the .coffee file as shown below.
indian_team = function() {
var Captain, WiseCaptain, first, i, len, member, others, results, second, team;
first = arguments[0], second = arguments[1], others = 3 <= arguments.length ?
slice.call(arguments, 2) : [];
Captain = first;
WiseCaptain = second;
team = others;
console.log("Captain: " + Captain);
console.log("Wise captain: " + WiseCaptain);
console.log("Other team members:: ");
results = [];
for (i = 0, len = others.length; i < len; i++) {
member = others[i];
results.push(console.log(member));
}
return results;
};
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"];
indian_team.apply(null, squad);
141
CoffeeScript
}).call(this);
Now, open the command prompt again and run the CoffeeScript file as shown below.
142
17. CoffeeScript – Date CoffeeScript
The Date object is a data-type built into the JavaScript language. Date objects are created as
new Date( ).
Once a Date object is created, a number of methods allow you to operate on it. Most methods
simply allow you to get and set the year, month, day, hour, minute, second, and millisecond
fields of the object, using either local time or UTC (universal, or GMT) time.
The ECMAScript standard requires the Date object to be able to represent any date and time, to
millisecond precision, within 100 million days before or after 1/1/1970. This is a range of plus or
minus 273,785 years, so JavaScript can represent date and time till the year 275755.
Similar to other JavaScript objects we can also use the date object of our CoffeeScript code.
Date Methods
Following is the list of methods of the Date object of JavaScript. Click on the name of these
methods to get an example demonstrating their usage in CoffeeScript.
Method Description
Returns the day of the month for the specified date according to
getDate()
local time.
Returns the day of the week for the specified date according to
getDay()
local time.
getFullYear() Returns the year of the specified date according to local time.
getHours() Returns the hour in the specified date according to local time.
getMinutes() Returns the minutes in the specified date according to local time.
getMonth() Returns the month in the specified date according to local time.
getSeconds() Returns the seconds in the specified date according to local time.
getTimezoneOffset() Returns the time-zone offset in minutes for the current locale.
Returns the day (date) of the month in the specified date according
getUTCDate()
to universal time.
getUTCFullYear() Returns the year in the specified date according to universal time.
getUTCHours() Returns the hours in the specified date according to universal time.
143
CoffeeScript
Sets the day of the month for a specified date according to local
setDate()
time.
setFullYear() Sets the full year for a specified date according to local time.
setHours() Sets the hours for a specified date according to local time.
setMilliseconds() Sets the milliseconds for a specified date according to local time.
setMinutes() Sets the minutes for a specified date according to local time.
setMonth() Sets the month for a specified date according to local time.
setSeconds() Sets the seconds for a specified date according to local time.
setUTCFullYear() Sets the full year for a specified date according to universal time.
setUTCHours() Sets the hour for a specified date according to universal time.
setUTCMinutes() Sets the minutes for a specified date according to universal time.
setUTCMonth() Sets the month for a specified date according to universal time.
setUTCSeconds() Sets the seconds for a specified date according to universal time.
Returns the "date" portion of the Date as a string, using the current
toLocaleDateString()
locale's conventions.
Returns the "time" portion of the Date as a string, using the current
toLocaleTimeString()
locale's conventions.
144
CoffeeScript
getDate() Method
Description
The getDate() method returns the day of the month for the specified date according to local time.
The value returned by getDate() is an integer between 1 and 31.
Syntax
Given below is the syntax of getDate() method.
Date.getDate()
Example
The following example demonstrates the usage of the getDate() method in CoffeeScript. Save
this code in a file with name date_getdate.coffee.
Open the command prompt and compile the .coffee file as shown below.
}).call(this);
Now, open the command prompt again, and run the CoffeeScript file as shown below.
145
CoffeeScript
getDay() Method
Description
The getDay() method returns the day of the week for the specified date according to local time.
The value returned by getDay() is an integer corresponding to the day of the week: 0 for Sunday,
1 for Monday, 2 for Tuesday, and so on.
Syntax
Given below is the syntax of getDay() method.
Date.getDay()
Example
The following example demonstrates the usage of the getDay() method in CoffeeScript. Save this
code in a file with name date_getday.coffee.
Open the command prompt and compile the .coffee file as shown below.
}).call(this);
Now, open the command prompt again, and run the CoffeeScript file as shown below.
146
CoffeeScript
getFullYear() Method
Description
The getFullYear() method returns the year of the specified date according to local time. The value
returned by getFullYear() is an absolute number. For dates between the years 1000 and 9999,
getFullYear() returns a four-digit number, for example, 2008.
Syntax
Given below is the syntax of getFullYear() method.
getFullYear()
Example
The following example demonstrates the usage of the getFullYear() method in CoffeeScript. Save
this code in a file with name date_getFullYear.coffee.
Open the command prompt and compile the .coffee file as shown below.
}).call(this);
Now, open the command prompt again, and run the CoffeeScript file as shown below.
147
CoffeeScript
getHours() Method
Description
The getHours() method returns the hour in the specified date according to local time. The value
returned by getHours() is an integer between 0 and 23.
Syntax
Given below is the syntax of getHours() method.
getHours()
Example
The following example demonstrates the usage of the getHours() method in CoffeeScript. Save
this code in a file with name date_gethours.coffee.
Open the command prompt and compile the .coffee file as shown below.
}).call(this);
Now, open the command prompt again, and run the CoffeeScript file as shown below.
148
CoffeeScript
getMilliseconds() Method
Description
The getMilliseconds () method returns the milliseconds in the specified date according to local
time. The value returned by getMilliseconds() is a number between 0 and 999.
Syntax
Given below is the syntax of getMilliseconds() method.
Date. getMilliseconds()
Example
The following example demonstrates the usage of the getMilliseconds() method in CoffeeScript.
Save this code in a file with name date_getmilliseconds.coffee.
Open the command prompt and compile the .coffee file as shown below.
}).call(this);
Now, open the command prompt again, and run the CoffeeScript file as shown below.
149
CoffeeScript
getMinutes() Method
Description
The getMinutes() method returns the minutes in the specified date according to local time. The
value returned by getMinutes() is an integer between 0 and 59.
Syntax
Given below is the syntax of getMinutes() method.
Date. getMinutes()
Example
The following example demonstrates the usage of the getMinutes() method in CoffeeScript. Save
this code in a file with name date_minutes.coffee.
Open the command prompt and compile the .coffee file as shown below.
}).call(this);
Now, open the command prompt again, and run the CoffeeScript file as shown below.
150
CoffeeScript
getMonth() Method
Description
The getMonth() method returns the month in the specified date according to local time. The value
returned by getMonth() is an integer between 0 and 11. 0 corresponds to January, 1 to February,
and so on.
Syntax
Given below is the syntax of getMonth() method.
Date. getMonth()
Example
The following example demonstrates the usage of the getMonth() method in CoffeeScript. Save
this code in a file with name date_getmonth.coffee.
Open the command prompt and compile the .coffee file as shown below.
}).call(this);
Now, open the command prompt again, and run the CoffeeScript file as shown below.
151
CoffeeScript
getUTCSeconds() Method
Description
The getSeconds() method returns the seconds in the specified date according to local time. The
value returned by getSeconds() is an integer between 0 and 59.
Syntax
Given below is the syntax of getSeconds() method.
Date.getSeconds()
Example
The following example demonstrates the usage of the getSeconds() method in CoffeeScript. Save
this code in a file with name date_getseconds.coffee.
Open the command prompt and compile the .coffee file as shown below.
}).call(this);
Now, open the command prompt again, and run the CoffeeScript file as shown below.
152
CoffeeScript
getTime() Method
Description
The getTime() method returns the numeric value corresponding to the time for the specified date
according to universal time. The value returned by the getTime method is the number of
milliseconds since 1 January 1970 00:00:00.
Syntax
Given below is the syntax of getTime() method.
Date.getTime()
Example
The following example demonstrates the usage of the getTime() method in CoffeeScript. Save
this code in a file with name date_gettime.coffee.
Open the command prompt and compile the .coffee file as shown below.
}).call(this);
Now, open the command prompt again, and run the CoffeeScript file as shown below.
153
CoffeeScript
getTimezoneOffset() Method
Description
The getTimezoneOffset() method returns the time-zone offset in minutes for the current locale.
The time-zone offset is the minutes in difference, the Greenwich Mean Time (GMT) is relative to
your local time.
For example, if your time zone is GMT+10, -600 will be returned. Daylight savings time prevents
this value from being a constant.
Syntax
Given below is the syntax of getTimezoneOffset() method.
Date. getTimezoneOffset()
Example
The following example demonstrates the usage of the getTimezoneOffset() method in
CoffeeScript. Save this code in a file with name date_gettimezoneoffset.coffee.
Open the command prompt and compile the .coffee file as shown below.
}).call(this);
Now, open the command prompt again, and run the CoffeeScript file as shown below.
154
CoffeeScript
getUTCDate() Method
Description
The getUTCDate() method returns the day of the month in the specified date according to
universal time. The value returned by getUTCDateis an integer between 1 and 31.
Syntax
Given below is the syntax of getUTCDate() method.
Date. getUTCDate()
Example
The following example demonstrates the usage of the getUTCDate() method in CoffeeScript.
Save this code in a file with name date_getutcdate.coffee.
Open the command prompt and compile the .coffee file as shown below.
}).call(this);
Now, open the command prompt again, and run the CoffeeScript file as shown below.
155
CoffeeScript
getUTCDay() method
Description
The getUTCDay() method returns the day of the week in the specified date according to universal
time. The value returned by getUTCDay() is an integer corresponding to the day of the week: 0
for Sunday, 1 for Monday, 2 for Tuesday, and so on.
Syntax
Given below is the syntax of getUTCDay() method.
Date. getUTCDay()
Example
The following example demonstrates the usage of the getUTCDay() method in CoffeeScript. Save
this code in a file with name date_getutcday.coffee.
Open the command prompt and compile the .coffee file as shown below.
}).call(this);
Now, open the command prompt again, and run the CoffeeScript file as shown below.
156
CoffeeScript
getUTCFullYear() Method
Description
The getUTCFullYear() method returns the year in the specified date according to universal time.
The value returned by getUTCFullYear() is an absolute number that is compliant with year-2000,
for example, 2008.
Syntax
Given below is the syntax of getUTCFullYear() method.
Date.getUTCFullYear()
Example
The following example demonstrates the usage of the getUTCFullYear() method in CoffeeScript.
Save this code in a file with name date_getutcfullyear.coffee.
Open the command prompt and compile the .coffee file as shown below.
}).call(this);
Now, open the command prompt again, and run the CoffeeScript file as shown below.
157
CoffeeScript
getUTCHours() Method
Description
The getUTCHours() method returns the hours in the specified date according to universal time.
The value returned by getUTCHours() is an integer between 0 and 23.
Syntax
Given below is the syntax of getUTCHours() method.
Date.getUTCHours()
Example
The following example demonstrates the usage of the getUTCHours() method in CoffeeScript.
Save this code in a file with name date_getutchours.coffee.
dt = new Date()
console.log "The UTC hours in the specified date is : " + dt.getUTCHours()
Open the command prompt and compile the .coffee file as shown below.
dt = new Date();
}).call(this);
Now, open the command prompt again, and run the CoffeeScript file as shown below.
158
CoffeeScript
getUTCMilliseconds() Method
Description
The getUTCMilliseconds() method returns the milliseconds in the specified date according to
universal time. The value returned by getUTCMilliseconds() is an integer between 0 and 999.
Syntax
Given below is the syntax of getUTCMilliseconds() method.
Date.getUTCMilliseconds()
Example
The following example demonstrates the usage of the getUTCMilliseconds() method in
CoffeeScript. Save this code in a file with name date_getutcmilliseconds.coffee.
dt = new Date()
console.log "The UTC milliseconds in the specified date is : " +
dt.getUTCMilliseconds()
Open the command prompt and compile the .coffee file as shown below.
dt = new Date();
}).call(this);
Now, open the command prompt again, and run the CoffeeScript file as shown below.
159
CoffeeScript
getUTCMinutes() Method
Description
The getUTCMinutes() method returns the minutes in the specified date according to universal
time. The value returned by getUTCMinutes() is an integer between 0 and 59.
Syntax
Given below is the syntax of getUTCMinutes() method.
Date.getUTCMinutes()
Example
The following example demonstrates the usage of the getUTCMinutes() method in CoffeeScript.
Save this code in a file with name date_getutcminutes.coffee.
dt = new Date()
console.log "The UTC minutes in the specified date is : " + dt.getUTCMinutes()
Open the command prompt and compile the .coffee file as shown below.
dt = new Date();
}).call(this);
Now, open the command prompt again, and run the CoffeeScript file as shown below.
160
CoffeeScript
getUTCMonth() Method
Description
The getUTCMonth() method returns the month in the specified date according to universal time.
The value returned by getUTCMonth() is an integer between 0 and 11 corresponding to the
month. 0 for January, 1 for February, 2 for March, and so on.
Syntax
Given below is the syntax of getUTCMonth() method.
Date.getUTCMonth()
Example
The following example demonstrates the usage of the getUTCMonth() method in CoffeeScript.
Save this code in a file with name date_getutcmonth.coffee.
dt = new Date()
console.log "The UTC minutes in the specified date is : " + dt.getUTCMonth()
Open the command prompt and compile the .coffee file as shown below.
dt = new Date();
}).call(this);
Now, open the command prompt again, and run the CoffeeScript file as shown below.
161
CoffeeScript
getUTCSeconds() Method
Description
The getUTCSeconds() method returns the seconds in the specified date according to universal
time. The value returned by getUTCSeconds() is an integer between 0 and 59.
Syntax
Given below is the syntax of getUTCSeconds() method.
Date.getUTCSeconds()
Example
The following example demonstrates the usage of the getUTCSeconds() method in CoffeeScript.
Save this code in a file with name date_getutcseconds.coffee.
dt = new Date()
console.log "The UTC minutes in the specified date is : " + dt.getUTCSeconds()
Open the command prompt and compile the .coffee file as shown below.
dt = new Date();
}).call(this);
Now, open the command prompt again, and run the CoffeeScript file as shown below.
162
CoffeeScript
getYear() Method
Description
The getYear() method returns the year for a specified date according to universal time.
Syntax
Given below is the syntax of getYear() method.
Date.getYear()
Example
The following example demonstrates the usage of the getYear() method in CoffeeScript. Save
this code in a file with name date_getyear.coffee.
Open the command prompt and compile the .coffee file as shown below.
year = dt.getYear();
console.log(year);
}).call(this);
Now, open the command prompt again, and run the CoffeeScript file as shown below.
2016
163
CoffeeScript
setDate() Method
Description
The setDate() method sets the day of the month for a specified date according to local time.
Syntax
Given below is the syntax of setDate() method.
Date.setDate dayValue
Example
The following example demonstrates the usage of the setDate() method in CoffeeScript. Save
this code in a file with name date_setdate.coffee.
Open the command prompt and compile the .coffee file as shown below.
dt.setDate(24);
console.log(dt);
}).call(this);
Now, open the command prompt again, and run the CoffeeScript file as shown below.
164
CoffeeScript
setFullYear() Method
Description
The setFullYear() method sets the full year for a specified date according to local time.
Syntax
Given below is the syntax of setFullYear() method.
Example
The following example demonstrates the usage of the setFullYear() method in CoffeeScript. Save
this code in a file with name date_setfullyear.coffee.
Open the command prompt and compile the .coffee file as shown below.
dt.setFullYear(2014);
console.log(dt);
}).call(this);
Now, open the command prompt again, and run the CoffeeScript file as shown below.
165
CoffeeScript
setHours() Method
Description
The setHours() method sets the hour for a specified date according to local time.
Syntax
Given below is the syntax of setHours() method.
Parameter Detail
hoursValue − An integer between 0 and 23, representing the hour.
secondsValue − An integer between 0 and 59, representing the seconds. If you specify
the secondsValue parameter, you must also specify the minutesValue.
msValue −A number between 0 and 999, representing the milliseconds. If you specify the
msValue parameter, you must also specify the minutesValue and secondsValue.
If you do not specify the minutesValue, secondsValue, and msValue parameters, the values
returned from the getUTCMinutes, getUTCSeconds, and getMilliseconds methods are used.
Example
The following example demonstrates the usage of the setUTCHours() method in CoffeeScript.
Save this code in a file with name date_setutchours.coffee.
Open the Node.js command prompt and compile the .coffee file as shown below.
dt.setHours(15);
166
CoffeeScript
console.log(dt);
}).call(this);
Now, open the command prompt again, and run the CoffeeScript file as shown below.
setMilliseconds() Method
Description
The setMilliseconds() method sets the milliseconds for a specified date according to local time.
Syntax
Given below is the syntax of setMilliseconds() method.
Date.setMilliseconds(millisecondsValue)
Example
The following example demonstrates the usage of the setMilliseconds() method in CoffeeScript.
Save this code in a file with name date_setmilliseconds.coffee.
Open the command prompt and compile the .coffee file as shown below.
167
CoffeeScript
dt.setFullYear(1010);
console.log(dt);
}).call(this);
Now, open the command prompt again, and run the CoffeeScript file as shown below.
setMinutes() Method
Description
The setMinutes() method sets the minutes for a specified date according to local time.
Syntax
Given below is the syntax of setMinutes() method.
Parameter Detail
secondsValue − An integer between 0 and 59, representing the seconds. If you specify
the secondsValue parameter, you must also specify the minutesValue.
msValue −A number between 0 and 999, representing the milliseconds. If you specify the
msValue parameter, you must also specify the minutesValue and secondsValue.
If you do not specify the secondsValue and msValue parameters, the values returned from
getSeconds and getMilliseconds methods are used.
Example
The following example demonstrates the usage of the setMinutes() method in CoffeeScript. Save
this code in a file with name date_setminutes.coffee.
Open the command prompt and compile the .coffee file as shown below.
168
CoffeeScript
dt.setMinutes(45);
console.log(dt);
}).call(this);
Now, open the command prompt again, and run the CoffeeScript file as shown below.
setMonth() Method
Description
The setMonth() method sets the month for a specified date according to local time.
Syntax
Given below is the syntax of setMonth() method.
Date.setMonth(monthValue[, dayValue])
Parameter Detail
monthValue − An integer between 0 and 11 (representing the months January through
December).
msValue −A number between 0 and 999, representing the milliseconds. If you specify the
msValue parameter, you must also specify the minutesValue and secondsValue.
If you do not specify the dayValue parameter, the value returned from the getDate method is
used. If a parameter you specify is outside of the expected range, setMonth attempts to update
169
CoffeeScript
the date information in the Date object accordingly. For example, if you use 15 for monthValue,
the year will be incremented by 1 (year + 1), and 3 will be used for month.
Example
The following example demonstrates the usage of the setMonth() method in CoffeeScript. Save
this code in a file with name date_setmonth.coffee.
Open the command prompt and compile the .coffee file as shown below.
dt.setMonth(5);
console.log(dt);
}).call(this);
Now, open the command prompt again, and run the CoffeeScript file as shown below.
setSeconds() Method
Description
The setSeconds() method sets the seconds for a specified date according to local time
Syntax
170
CoffeeScript
Date.setSeconds(secondsValue[, msValue])
Parameter Detail
secondsValue − An integer between 0 and 59.
msValue − A number between 0 and 999, representing the milliseconds.
If you do not specify the msValue parameter, the value returned from the getMilliseconds method
is used. If a parameter you specify is outside of the expected range, setSeconds attempts to
update the date information in the Date object accordingly. For example, if you use 100 for
secondsValue, the minutes stored in the Date object will be incremented by 1, and 40 will be
used for seconds.
Example
The following example demonstrates the usage of the setSeconds() method in CoffeeScript. Save
this code in a file with name date_setseconds.coffee.
Open the command prompt and compile the .coffee file as shown below.
dt.setSeconds(25);
console.log(dt);
}).call(this);
Now, open the command prompt again, and run the CoffeeScript file as shown below.
171
CoffeeScript
setTime() Method
Description
The setTime() method sets the Date object to the time represented by a number of milliseconds
since January 1, 1970, 00:00:00 UTC.
Syntax
Given below is the syntax of setTime() method.
Date.setTime(timeValue)
Parameter Detail
timeValue − An integer representing the number of milliseconds since 1 January 1970,
00:00:00 UTC.
Example
The following example demonstrates the usage of the setTime() method in CoffeeScript. Save
this code in a file with name date_settime.coffee.
Open the command prompt and compile the .coffee file as shown below.
console.log(dt);
172
CoffeeScript
}).call(this);
Now, open the command prompt again, and run the CoffeeScript file as shown below.
setUTCDate() Method
Description
The setUTCDate() method sets the day of the month for a specified date according to universal
time.
Syntax
Given below is the syntax of setUTCDate() method.
Date.setUTCDate(dayValue)
Parameter Detail
dayValue − An integer from 1 to 31, representing the day of the month.
Example
The following example demonstrates the usage of the setUTCDate() method in CoffeeScript. Save
this code in a file with name date_setutcdate.coffee.
Open the command prompt and compile the .coffee file as shown below.
dt.setUTCDate(20);
console.log(dt);
}).call(this);
Now, open the command prompt again, and run the CoffeeScript file as shown below.
setUTCFullYear() Method
Description
The setUTCFullYear() method sets the full year for a specified date according to universal time.
Syntax
Given below is the syntax of setUTCFullYear() method.
Parameter Detail
yearValue − An integer specifying the numeric value of the year, for example, 2008.
dayValue −An integer between 1 and 31 representing the day of the month. If you specify
the dayValue parameter, you must also specify the monthValue.
If you do not specify the monthValue and dayValue parameters, the values returned from the
getMonth and getDate methods are used. If a parameter you specify is outside of the expected
range, setUTCFullYear attempts to update the other parameters and the date information in the
Date object accordingly. For example, if you specify 15 for monthValue, the year is incremented
by 1 (year + 1), and 3 is used for the month.
Example
The following example demonstrates the usage of the setUTCFullYear() method in CoffeeScript.
Save this code in a file with name date_setutcfullYear.coffee.
174
CoffeeScript
dt.setUTCFullYear 20
console.log dt
Open the command prompt and compile the .coffee file as shown below.
dt.setUTCFullYear(20);
console.log(dt);
}).call(this);
Now, open the command prompt again, and run the CoffeeScript file as shown below.
setUTCHours() Method
Description
The setUTCHours() method sets the hour for a specified date according to local time.
Syntax
Given below is the syntax of setUTCHours() method.
Parameter Detail
hoursValue − An integer between 0 and 23, representing the hour.
secondsValue − An integer between 0 and 59, representing the seconds. If you specify
the secondsValue parameter, you must also specify the minutesValue.
msValue −A number between 0 and 999, representing the milliseconds. If you specify the
msValue parameter, you must also specify the minutesValue and secondsValue.
If you do not specify the minutesValue, secondsValue, and msValue parameters, the values
returned from the getUTCMinutes, getUTCSeconds, and getUTCMilliseconds methods are used.
If a parameter you specify is outside the expected range, setUTCHours attempts to update the
date information in the Date object accordingly. For example, if you use 100 for secondsValue,
the minutes will be incremented by 1 (min + 1), and 40 will be used for seconds.
Example
The following example demonstrates the usage of the setUTCHours() method in CoffeeScript.
Save this code in a file with name date_setutchours.coffee.
Open the command prompt and compile the .coffee file as shown below.
dt.setUTCHours(15);
console.log(dt);
}).call(this);
Now, open the command prompt again, and run the CoffeeScript file as shown below.
176
CoffeeScript
setUTCMilliseconds() Method
Description
The setUTCMilliseconds() method sets the milliseconds for a specified date according to
universal time.
Syntax
Given below is the syntax of setMinutes() method.
Date.setUTCMilliseconds(millisecondsValue)
Parameter Detail
millisecondsValue − A number between 0 and 999, representing the milliseconds.
If a parameter you specify is outside the expected range, setUTCMilliseconds attempts to update
the date information in the Date object accordingly. For example, if you use 1100 for
millisecondsValue, the seconds stored in the Date object will be incremented by 1, and 100 will
be used for milliseconds.
Example
The following example demonstrates the usage of the setUTCMilliseconds() method in
CoffeeScript. Save this code in a file with name date_setutcmilliseconds.coffee.
Open the command prompt and compile the .coffee file as shown below.
dt.setUTCMilliseconds(1100);
177
CoffeeScript
console.log(dt);
}).call(this);
Now, open the command prompt again, and run the CoffeeScript file as shown below.
setUTCMinutes() Method
Description
The setUTCMinutes() method sets the minutes for a specified date according to universal time.
Syntax
Given below is the syntax of setUTCMinutes() method.
Parameter Detail
minutesValue − An integer between 0 and 59, representing the minutes.
secondsValue − An integer between 0 and 59, representing the seconds. If you specify
the secondsValue parameter, you must also specify the minutesValue.
msValue − A number between 0 and 999, representing the milliseconds. If you specify
the msValue parameter, you must also specify the minutesValue and secondsValue.
If you do not specify the secondsValue and msValue parameters, the values returned from
getUTCSeconds and getUTCMilliseconds methods are used.
If a parameter you specify is outside of the expected range, setUTCMinutes attempts to update
the date information in the Date object accordingly. For example, if you use 100 for
secondsValue, the minutes (minutesValue) will be incremented by 1 (minutesValue + 1), and 40
will be used for seconds.
Example
The following example demonstrates the usage of the setUTCMinutes() method in CoffeeScript.
Save this code in a file with name date_setutcminutes.coffee.
178
CoffeeScript
Open the command prompt and compile the .coffee file as shown below.
dt.setUTCMilliseconds(1100);
console.log(dt);
}).call(this);
Now, open the command prompt again, and run the CoffeeScript file as shown below.
setUTCMonth() Method
Description
The setUTCMonth() method sets the month for a specified date according to universal time.
Syntax
Given below is the syntax of setUTCMonth() method.
Date.setUTCMonth( monthvalue )
Parameter Detail
monthValue − An integer between 0 and 11, representing the month.
Example
The following example demonstrates the usage of the setUTCMonth() method in CoffeeScript.
Save this code in a file with name date_setutcmonth.coffee.
179
CoffeeScript
Open the command prompt and compile the .coffee file as shown below.
dt.setUTCMonth(2);
console.log(dt);
}).call(this);
Now, open the command prompt again, and run the CoffeeScript file as shown below.
setUTCSeconds() Method
Description
The setUTCSeconds() method sets the seconds for a specified date according to universal time.
Syntax
Given below is the syntax of setUTCSeconds() method.
Date.setUTCSeconds(secondsValue[, msValue])
Parameter Detail
180
CoffeeScript
If you do not specify the msValue parameter, the value returned from the getUTCMilliseconds
methods is used.
If a parameter you specify is outside the expected range, setUTCSeconds attempts to update
the date information in the Date object accordingly. For example, if you use 100 for
secondsValue, the minutes stored in the Date object will be incremented by 1, and 40 will be
used for seconds.
Example
The following example demonstrates the usage of the setUTCSeconds() method in CoffeeScript.
Save this code in a file with name date_setutcseconds.coffee.
Open the command prompt and compile the .coffee file as shown below.
dt.setUTCSeconds(2);
console.log(dt);
}).call(this);
Now, open the command prompt again, and run the CoffeeScript file as shown below.
181
CoffeeScript
setYear() Method
Description
The setYear() method sets the year for a specified date according to universal time.
Syntax
Given below is the syntax of setYear() method.
Date.setYear(yearValue)
Parameter Detail
yearValue − An integer value.
Example
The following example demonstrates the usage of the setYear() method in CoffeeScript. Save
this code in a file with name date_setyear.coffee.
Open the command prompt and compile the .coffee file as shown below.
dt.setYear(2000);
console.log(dt);
}).call(this);
Now, open the command prompt again, and run the CoffeeScript file as shown below.
182
CoffeeScript
toDateString() Method
Description
The toDateString() method returns the date portion of a Date object in human readable form.
Syntax
Given below is the syntax of toDateString() method.
Date.toDateString()
Return Value
Returns the date portion of a Date object in human readable form.
Example
The following example demonstrates the usage of the toDateString() method in CoffeeScript.
Save this code in a file with name date_todatestring.coffee.
Open the command prompt and compile the .coffee file as shown below.
dt.toDateString();
console.log(dt);
183
CoffeeScript
}).call(this);
Now, open the command prompt again, and run the CoffeeScript file as shown below.
toLocaleDateString() Method
Description
The toLocaleDateString() method converts a date to a string, returning the "date" portion using
the operating system's locale's conventions.
Syntax
Given below is the syntax of toLocaleDateString() method.
Date.toLocaleDateString()
Return Value
Returns the "date" portion using the operating system's locale's conventions.
Example
The following example demonstrates the usage of the toLocaleDateString () method in
CoffeeScript. Save this code in a file with name date_tolocaledatestring.coffee.
Open the command prompt and compile the .coffee file as shown below.
184
CoffeeScript
dt.toLocaleDateString();
console.log(dt);
}).call(this);
Now, open the command prompt again, and run the CoffeeScript file as shown below.
toLocaleString() Method
Description
The toLocaleString() method converts a date to a string, using the operating system's local
conventions.
The toLocaleString method relies on the underlying operating system in formatting dates. It
converts the date to a string using the formatting convention of the operating system where the
script is running. For example, in the United States, the month appears before the date
(04/15/98), whereas in Germany the date appears before the month (15.04.98).
Syntax
Given below is the syntax of toLocaleString() method.
Date.toLocaleString()
Return Value
Returns the formatted date in a string format.
Example
The following example demonstrates the usage of the toLocaleString() method in CoffeeScript.
Save this code in a file with name date_tolocalestring.coffee.
Open the command prompt and compile the .coffee file as shown below.
185
CoffeeScript
console.log(dt.toLocaleString());
}).call(this);
Now, open the command prompt again, and run the CoffeeScript file as shown below.
7/28/1993, 2:39:07 PM
toLocaleTimeString() Method
Description
The toLocaleTimeString() method converts a date to a string, returning the "date" portion using
the current locale's conventions.
The toLocaleTimeString method relies on the underlying operating system in formatting dates.
It converts the date to a string using the formatting convention of the operating system where
the script is running. For example, in the United States, the month appears before the date
(04/15/98), whereas in Germany, the date appears before the month (15.04.98).
Syntax
Given below is the syntax of toLocaleTimeString() method.
Date.toLocaleTimeString()
Return Value
Returns the formatted date in a string format.
Example
The following example demonstrates the usage of the toLocaleTimeString() method in
CoffeeScript. Save this code in a file with name date_tolocaletimestring.coffee.
186
CoffeeScript
console.log dt.toLocaleTimeString()
Open the command prompt and compile the .coffee file as shown below.
console.log(dt.toLocaleTimeString());
}).call(this);
Now, open the Node.js command prompt again, and run the CoffeeScript file as shown below.
2:39:07 PM
toTimeString() Method
Description
The toTimeStrin() method returns the time portion of a Date object in human readable form.
Syntax
Given below is the syntax of toTimeString() method.
Date.toTimeString()
Return Value
Returns the time portion of a Date object in human readable form.
Example
The following example demonstrates the usage of the toTimeString() method in CoffeeScript.
Save this code in a file with name date_totimestring .coffee.
187
CoffeeScript
Open the command prompt and compile the .coffee file as shown below.
console.log(dt.toTimeString());
}).call(this);
Now, open the command prompt again, and run the CoffeeScript file as shown below.
toTimeString Method
Description
The toUTCString() Method returns the time portion of a Date object in human readable form.
Syntax
Given below is the syntax of toUTCString() method.
Date.toUTCString()
Return Value
Returns converted date to a string, using the universal time convention.
Example
188
CoffeeScript
The following example demonstrates the usage of the toUTCString() method in CoffeeScript.
Save this code in a file with name date_toutcstring.coffee.
Open the command prompt and compile the .coffee file as shown below.
console.log(dt.toUTCString());
}).call(this);
Now, open the command prompt again, and run the CoffeeScript file as shown below.
189
18. CoffeeScript – Math CoffeeScript
The Math object of JavaScript provides you properties and methods for mathematical constants
and functions. Unlike other global objects, Math is not a constructor. All the properties and
methods of Math are static and can be called by using Math as an object without creating it.
Thus, you refer to the constant pi as Math.PI and you call the sine function as Math.sin(x),
where x is the method's argument. We can use the JavaScript's Math object in our CoffeeScript
code to perform math operations.
Mathematical constants
If we want to use any common mathematical constants like pi or e, we can use them using the
JavaScript's Math object.
Following is the list of the Math constants provided by the Math object of JavaScript
Property Description
SQRT1_2 Square root of 1/2; equivalently, 1 over the square root of 2, approximately 0.707.
Example
The following example demonstrates the usage of the mathematical constants provided by
JavaScript in CoffeeScript. Save this code in a file with name math_example.coffee
e_value = Math.E
console.log "The value of the constant E is: " + e_value
LN2_value = Math.LN2
console.log "The value of the constant LN2 is: " + LN2_value
LN10_value = Math.LN10
console.log "The value of the constant LN10 is: " + LN10_value
LOG2E_value = Math.LOG2E
190
CoffeeScript
LOG10E_value = Math.LOG10E
console.log "The value of the constant LOG10E is: " + LOG10E_value
PI_value = Math.PI
console.log "The value of the constant PI is: " + PI_value
SQRT1_2_value = Math.SQRT1_2
console.log "The value of the constant SQRT1_2 is: " + SQRT1_2_value
SQRT2_value = Math.SQRT2
console.log "The value of the constant SQRT2 is: " + SQRT2_value
Open the command prompt and compile the .coffee file as shown below.
e_value = Math.E;
LN2_value = Math.LN2;
LN10_value = Math.LN10;
LOG2E_value = Math.LOG2E;
191
CoffeeScript
LOG10E_value = Math.LOG10E;
PI_value = Math.PI;
SQRT1_2_value = Math.SQRT1_2;
SQRT2_value = Math.SQRT2;
}).call(this);
Now, open the command prompt again and run the CoffeeScript file as shown below.
Math Methods
In addition to properties, the Math object also provides methods. Following is the list of methods
of the Math object of JavaScript. Click on the name of these methods to get an example
demonstrating their usage in CoffeeScript
192
CoffeeScript
Method Description
exp() Returns EN, where N is the argument, and E is Euler's constant, the base of
the natural logarithm.
pow() Returns base to the exponent power, that is, base exponent.
abs() Method
Description
This method accepts an integer and returns the absolute value of the given integer.
Syntax
Following is the syntax of this method.
Math.abs( x )
Example
The following example demonstrates the usage of the abs() method in CoffeeScript. Save this
code in a file with name math_abs.coffee.
value = Math.abs(-1);
193
CoffeeScript
value = Math.abs(null);
console.log "The absolute value of null is : " + value
value = Math.abs(20);
console.log "The absolute value of 20 is : " + value
Open the command prompt and compile the .coffee file as shown below.
value = Math.abs(-1);
value = Math.abs(null);
value = Math.abs(20);
}).call(this);
Now, open the command prompt again, and run the CoffeeScript file as shown below.
194
CoffeeScript
acos() Method
Description
The acos() method accepts an number and returns its arc-cosine in radians. It returns a numeric
value between 0 and pi radians for x between -1 and 1. If the value of number is outside this
range, it returns NaN.
Syntax
Given below is the syntax of acos() method of JavaScript. We can use the same method in the
CoffeeScript code.
Math.acos( x )
Example
The following example demonstrates the usage of the acos() method in CoffeeScript. Save this
code in a file with name math_acos.coffee.
value = Math.acos -1
console.log "The arc cosine value of -1 is : " + value
value = Math.acos 20
console.log "The arc cosine value of 20 is : " + value
Open the command prompt and compile the .coffee file as shown below.
value = Math.acos(-1);
value = Math.acos(null);
195
CoffeeScript
value = Math.acos(20);
}).call(this);
Now, open the command prompt again, and run the CoffeeScript file as shown below.
asin() Method
Description
The asin() method accepts an integer value and returns its arc-sine in radians. The asin method
returns a numerical value between -pi/2 and pi/2 radians for x between -1 and 1. If the value of
number is outside this range, it returns NaN.
Syntax
Given below is the syntax of asin() method of JavaScript. We can use the same method in the
CoffeeScript code.
Math.asin( x )
Example
The following example demonstrates the usage of the asin() method in CoffeeScript. Save this
code in a file with name math_asin.coffee.
value = Math.asin -1
console.log "The arc sine value of -1 is : " + value
value = Math.asin 20
196
CoffeeScript
Open the command prompt and compile the .coffee file as shown below.
value = Math.asin(-1);
value = Math.asin(null);
value = Math.asin(20);
}).call(this);
Now, open the command prompt again, and run the CoffeeScript file as shown below.
atan() Method
Description
The atan() method accepts a number and returns its arctangent value in radians. This method
returns a numeric value between -pi/2 and pi/2 radians.
197
CoffeeScript
Syntax
Given below is the syntax of atan() method of JavaScript. We can use the same method in the
CoffeeScript code.
Math.atan( x )
Example
The following example demonstrates the usage of the atan() method in CoffeeScript. Save this
code in a file with name math_atan.coffee.
value = Math.atan -1
console.log "The arc tangent value of -1 is : " + value
value = Math.atan 20
console.log "The arc tangent value of 20 is : " + value
Open the command prompt and compile the .coffee file as shown below.
value = Math.atan(-1);
value = Math.atan(null);
value = Math.atan(20);
198
CoffeeScript
}).call(this);
Now, open the command prompt again, and run the CoffeeScript file as shown below.
atan2() Method
Description
The atan2() method accepts two numbers and returns the arctangent value in radians. This
method returns a numeric value between -pi and pi representing the angle theta of an (x, y)
point.
Syntax
Given below is the syntax of atan2() method of JavaScript. We can use the same method in the
CoffeeScript code.
Math.atan( x )
Example
The following example demonstrates the usage of the atan2() method in CoffeeScript. Save this
code in a file with name math_atan2.coffee.
199
CoffeeScript
Open the command prompt and compile the .coffee file as shown below.
value = Math.atan(-1);
value = Math.atan(null);
value = Math.atan(20);
}).call(this);
Now, open the command prompt again, and run the CoffeeScript file as shown below.
ceil() Method
Description
The ceil() method accepts a number and returns its ceil value.
Syntax
200
CoffeeScript
Given below is the syntax of ceil() method of JavaScript. We can use the same method in the
CoffeeScript code.
Math.ceil( x )
Example
The following example demonstrates the usage of the ceil() method in CoffeeScript. Save this
code in a file with name math_ceil.coffee.
Open the command prompt and compile the .coffee file as shown below.
value = Math.ceil(90.15);
value = Math.ceil(15.90);
value = Math.ceil(-90.15);
201
CoffeeScript
value = Math.ceil(-15.90);
}).call(this);
Now, open the command prompt again, and run the CoffeeScript file as shown below.
cos() Method
Description
The cos() method accepts a number and returns its cosine value which is between -1 and 1.
Syntax
Given below is the syntax of cos() method of JavaScript. We can use the same method in the
CoffeeScript code.
Math.cos( x )
Example
The following example demonstrates the usage of the cos() method in CoffeeScript. Save this
code in a file with name math_cos.coffee.
value = Math.cos 90
console.log "The cosine value of 90 is : " + value
value = Math.cos -1
console.log "The cosine value of -1 is : " + value
Open the command prompt and compile the .coffee file as shown below.
value = Math.cos(90);
value = Math.cos(-1);
}).call(this);
Now, open the command prompt again, and run the CoffeeScript file as shown below.
exp() Method
Description
The exp() method accepts a number and returns its Ex value. Where x is the argument, and E is
Euler's constant the base of the natural logarithms
203
CoffeeScript
Syntax
Given below is the syntax of exp() method of JavaScript. We can use the same method in the
CoffeeScript code.
Math.exp ( x )
Example
The following example demonstrates the usage of the exp() method in CoffeeScript. Save this
code in a file with name math_exp.coffee.
value = Math.exp 1
console.log "The exponential value of 1 is : " + value
value = Math.exp 52
console.log "The exponential value of 52 is : " + value
Open the command prompt and compile the .coffee file as shown below.
value = Math.exp(1);
value = Math.exp(52);
value = Math.exp(0.78);
}).call(this);
Now, open the command prompt again, and run the CoffeeScript file as shown below.
floor() Method
Description
The floor() method accepts a number and returns its floor value.
Syntax
Given below is the syntax of floor() method of JavaScript. We can use the same method in the
CoffeeScript code.
Math.floor ( x )
Example
The following example demonstrates the usage of the floor() method in CoffeeScript. Save this
code in a file with name math_floor.coffee.
Open the command prompt and compile the .coffee file as shown below.
205
CoffeeScript
value = Math.floor(10.3);
value = Math.floor(30.9);
value = Math.floor(-2.2);
}).call(this);
Now, open the Node.js command prompt again, and run the CoffeeScript file as shown below.
log() Method
Description
The log() method accepts a number and returns its the natural logarithm (base E) of a number.
If the value of number is negative, the return value is always NaN.
Syntax
Given below is the syntax of log() method of JavaScript. We can use the same method in the
CoffeeScript code.
Math.log ( x )
206
CoffeeScript
Example
The following example demonstrates the usage of the log() method in CoffeeScript. Save this
code in a file with name math_log.coffee.
value = Math.log 10
console.log "The log value of 10 is : " + value
value = Math.log 0
console.log "The log value of 0 is : " + value
Open the command prompt and compile the .coffee file as shown below.
value = Math.log(10);
value = Math.log(0);
value = Math.log(100);
}).call(this);
Now, open the command prompt again, and run the CoffeeScript file as shown below.
207
CoffeeScript
max() Method
Description
The max() method accepts a set of numbers and returns the maximum value among the given
numbers. On calling this method without passing arguments it returns -Infinity.
Syntax
Given below is the syntax of max() method of JavaScript. We can use the same method in the
CoffeeScript code.
Math.max ( x )
Example
The following example demonstrates the usage of the max() method in CoffeeScript. Save this
code in a file with name math_max.coffee.
value = Math.max 0, -1
console.log "The max value among (0, -1) is : " + value
Open the command prompt and compile the .coffee file as shown below.
208
CoffeeScript
console.log("The max value among (10, 20, -1, 100) is : " + value);
}).call(this);
Now, open the command prompt again, and run the CoffeeScript file as shown below.
min() Method
Description
The min() method accepts a set of numbers and returns the minimum value among the given
numbers. On calling this method without passing arguments it returns +Infinity.
Syntax
Given below is the syntax of min() method of JavaScript. We can use the same method in the
CoffeeScript code.
Math.min ( x )
Example
The following example demonstrates the usage of the min() method in CoffeeScript. Save this
code in a file with name math_min.coffee.
209
CoffeeScript
value = Math.min 0, -1
console.log "The min value among (0, -1) is : " + value
Open the command prompt and compile the .coffee file as shown below.
console.log("The min value among (10, 20, -1, 100) is : " + value);
}).call(this);
Now, open the command prompt again, and run the CoffeeScript file as shown below.
210
CoffeeScript
pow() Method
Description
The pow() method accepts two numbers, a base and an exponent and this method returns the
base to the exponent power, that is, baseexponent.
Syntax
Given below is the syntax of pow() method of JavaScript. We can use the same method in the
CoffeeScript code.
Math.pow ( x )
Example
The following example demonstrates the usage of the pow() method in CoffeeScript. Save this
code in a file with name math_pow.coffee.
value = Math.pow 7, 2
console.log "The value of pow(7,2) is : " + value
Open the command prompt and compile the .coffee file as shown below.
211
CoffeeScript
}).call(this);
Now, open the command prompt again, and run the CoffeeScript file as shown below.
random() Method
Description
The random() method returns a random number between 0 (inclusive) and 1 (exclusive).
Syntax
Given below is the syntax of random() method of JavaScript. We can use the same method in
the CoffeeScript code.
Math.random ( x )
212
CoffeeScript
Example
The following example demonstrates the usage of the random() method in CoffeeScript. Save
this code in a file with name math_random.coffee.
value = Math.random()
console.log "The first number is : " + value
value = Math.random()
console.log "The second number is : " + value
value = Math.random()
console.log "The third number is : " + value
Open the command prompt and compile the .coffee file as shown below.
value = Math.random();
value = Math.random();
value = Math.random();
}).call(this);
Now, open the command prompt again, and run the CoffeeScript file as shown below.
213
CoffeeScript
round() Method
Description
The round() method accepts a number and returns the value of a number rounded to the nearest
integer
Syntax
Given below is the syntax of round() method of JavaScript. We can use the same method in the
CoffeeScript code.
Math.round ( x )
Example
The following example demonstrates the usage of the round() method in CoffeeScript. Save this
code in a file with name math_round.coffee.
Open the command prompt and compile the .coffee file as shown below.
214
CoffeeScript
value = Math.round(0.5);
value = Math.round(20.7);
value = Math.round(-20.3);
}).call(this);
Now, open the command prompt again, and run the CoffeeScript file as shown below.
sin() Method
Description
The sin() method accepts a number and returns its sine value which is between -1 and 1.
Syntax
Given below is the syntax of sin() method of JavaScript. We can use the same method in the
CoffeeScript code.
Math.sin( x )
Example
The following example demonstrates the usage of the sin() method in CoffeeScript. Save this
code in a file with name sin.coffee.
215
CoffeeScript
value = Math.sin 90
console.log "The sine value of 90 is : " + value
Open the Node.js command prompt and compile the .coffee file as shown below.
value = Math.sin(90);
value = Math.sin(0.5);
}).call(this);
Now, open the command prompt again, and run the CoffeeScript file as shown below.
216
CoffeeScript
sqrt() Method
Description
The sqrt() method accepts a number and returns its square root value. If the value of a number
is negative, sqrt returns NaN.
Syntax
Given below is the syntax of sqrt() method of JavaScript. We can use the same method in the
CoffeeScript code.
Math.sqrt ( x )
Example
The following example demonstrates the usage of the sqrt() method in CoffeeScript. Save this
code in a file with name math_sqrt.coffee.
value = Math.sqrt 81
console.log "The square root of 81 is : " + value
value = Math.sqrt 13
console.log "The square root of 13 is : " + value
value = Math.sqrt -4
console.log "The square root of -4 is : " + value
Open the command prompt and compile the .coffee file as shown below.
217
CoffeeScript
value = Math.sqrt(0.5);
value = Math.sqrt(81);
value = Math.sqrt(13);
value = Math.sqrt(-4);
}).call(this);
Now, open the command prompt again, and run the CoffeeScript file as shown below.
tan() Method
Description
The tan() method accepts a number and returns its tangent value.
Syntax
Given below is the syntax of tan() method of JavaScript. We can use the same method in the
CoffeeScript code.
Math.tan ( x )
218
CoffeeScript
Example
The following example demonstrates the usage of the tan() method in CoffeeScript. Save this
code in a file with name math_tan.coffee.
value = Math.tan 90
console.log "The tangent value of 90 is : " + value
value = Math.tan(2*Math.PI/180)
console.log "The tangent value of 2*Math.PI/180 is : " + value
Open the Node.js command prompt and compile the .coffee file as shown below.
value = Math.tan(-30);
value = Math.tan(90);
}).call(this);
Now, open the Node.js command prompt again, and run the CoffeeScript file as shown below.
219
CoffeeScript
220
19. CoffeeScript – Exception Handling CoffeeScript
An exception (or exceptional event) is a problem that arises during the execution of a program.
When an Exception occurs, the normal flow of the program is disrupted and the
program/Application terminates abnormally, which is not recommended, therefore these
exceptions are to be handled.
An exception can occur for many different reasons. Here are some scenarios where an exception
occurs.
Exceptions in CoffeeScript
CoffeeScripts supports exception/error handling using the try catch and finally blocks. The
functionalities of these blocks are same as in JavaScript, the try block holds the exceptional
statements, the catch block has the action to be performed when an exception occurs, and the
finally block is used to execute the statements unconditionally.
Following are the syntaxes of try catch and finally blocks in CoffeeScript.
try
// Code to run
catch ( e )
// Code to run if an exception occurs
finally
// Code that is always executed regardless of
// an exception occurring
The try block must be followed by either exactly one catch block or one finally block (or one of
both). When an exception occurs in the try block, the exception is placed in e and the catch block
is executed. The optional finally block executes unconditionally after try/catch.
Example
The following example demonstrates the Exception handling using try and catch blocks in
CoffeeScript. In here, we are trying to use an undefined symbol in CoffeeScript operation and
we handled the error occurred using the try and catch blocks. Save this code in a file with the
name Exception_handling.coffee
221
CoffeeScript
try
x = y+20
console.log "The value of x is :" +x
catch e
console.log "exception/error occurred"
console.log "The STACKTRACE for the exception/error occurred is ::"
console.log e.stack
Open the command prompt and compile the .coffee file as shown below.
try {
x = y + 20;
console.log("The value of x is :" + x);
} catch (error) {
e = error;
console.log("exception/error occurred");
console.log("The STACKTRACE for the exception/error occurred is ::");
console.log(e.stack);
}
}).call(this);
Now, open the command prompt again and run the CoffeeScript file as shown below.
exception/error occurred
The STACKTRACE for the exception/error occurred is ::
ReferenceError: y is not defined
at Object.<anonymous>
(C:\Examples\strings_exceptions\Exception_handling.coffee:3:7)
222
CoffeeScript
at Object.<anonymous>
(C:\Examples\strings_exceptions\Exception_handling.coffee:2:1)
at Module._compile (module.js:413:34)
at Object.exports.run
(C:\Users\Tutorialspoint\AppData\Roaming\npm\node_modules\coffee-script\lib\coffee-
script\coffee-script.js:134:23)
at compileScript (C:\Users\Tutorialspoint\AppData\Roaming\npm\node_modules\coffee-
script\lib\coffee-script\command.js:224:29)
at compilePath (C:\Users\Tutorialspoint\AppData\Roaming\npm\node_modules\coffee-
script\lib\coffee-script\command.js:174:14)
at Object.exports.run
(C:\Users\Tutorialspoint\AppData\Roaming\npm\node_modules\coffee-script\lib\coffee-
script\command.js:98:20)
at Object.<anonymous>
(C:\Users\Tutorialspoint\AppData\Roaming\npm\node_modules\coffee-
script\bin\coffee:7:41)
at Module._compile (module.js:413:34)
at Object.Module._extensions..js (module.js:422:10)
at Module.load (module.js:357:32)
at Function.Module._load (module.js:314:12)
at Function.Module.runMain (module.js:447:10)
at startup (node.js:139:18)
at node.js:999:3
try
x = y+20
console.log "The value of x is :" +x
catch e
console.log "exception/error occurred"
console.log "The STACKTRACE for the exception/error occurred is ::"
console.log e.stack
finally
console.log "This is the statement of finally block"
Open the command prompt and compile the .coffee file as shown below.
223
CoffeeScript
try {
x = y + 20;
console.log("The value of x is :" + x);
} catch (error) {
e = error;
console.log("exception/error occurred");
console.log("The STACKTRACE for the exception/error occurred is ::");
console.log(e.stack);
} finally {
console.log("This is the statement of finally block");
}
}).call(this);
Now, open the command prompt again and run the CoffeeScript file as shown below.
exception/error occurred
The STACKTRACE for the exception/error occurred is ::
ReferenceError: y is not defined
at Object.<anonymous>
(C:\Examples\strings_exceptions\Exception_handling.coffee:3:7)
at Object.<anonymous>
(C:\Examples\strings_exceptions\Exception_handling.coffee:2:1)
at Module._compile (module.js:413:34)
at Object.exports.run
(C:\Users\Tutorialspoint\AppData\Roaming\npm\node_modules\coffee-script\lib\coffee-
script\coffee-script.js:134:23)
at compileScript (C:\Users\Tutorialspoint\AppData\Roaming\npm\node_modules\coffee-
script\lib\coffee-script\command.js:224:29)
224
CoffeeScript
at compilePath (C:\Users\Tutorialspoint\AppData\Roaming\npm\node_modules\coffee-
script\lib\coffee-script\command.js:174:14)
at Object.exports.run
(C:\Users\Tutorialspoint\AppData\Roaming\npm\node_modules\coffee-script\lib\coffee-
script\command.js:98:20)
at Object.<anonymous>
(C:\Users\Tutorialspoint\AppData\Roaming\npm\node_modules\coffee-
script\bin\coffee:7:41)
at Module._compile (module.js:413:34)
at Object.Module._extensions..js (module.js:422:10)
at Module.load (module.js:357:32)
at Function.Module._load (module.js:314:12)
at Function.Module.runMain (module.js:447:10)
at startup (node.js:139:18)
at node.js:999:3
Example
The following example demonstrates the usage of the throw statement in CoffeeScript. Save this
code in a file with name throw_example.coffee
myFunc = ->
a = 100
b = 0
try
if b == 0
throw ("Divided by zero error.")
else
c = a / b
catch e
console.log "Error: " + e
myFunc()
225
CoffeeScript
Open the command prompt and compile the .coffee file as shown below.
myFunc = function() {
var a, b, c, e, error;
a = 100;
b = 0;
try {
if (b === 0) {
throw "Divided by zero error.";
} else {
return c = a / b;
}
} catch (error) {
e = error;
return console.log("Error: " + e);
}
};
myFunc();
}).call(this);
Now, open the command prompt again and run the CoffeeScript file as shown below.
226
20. CoffeeScript – Regular Expressions CoffeeScript
Syntax
A regular expression in CoffeeScript is defined by placing the RegExp pattern between the
forward slashes as shown below.
pattern =/pattern/
Example
Following is an example of regular expressions in CoffeeScript. In here, we have created an
expression that finds out the data that is in bold (data between <b> and </b> tags). Save this
code in a file with name regex_example.coffee
Open the command prompt and compile the .coffee file as shown below.
regex = /<b>(.*)<\/b>/;
227
CoffeeScript
result = regex.exec(input_data);
console.log(result);
}).call(this);
Now, open the command prompt again and run the CoffeeScript file as shown below.
[ '<b>Tutorials Point.</b>',
'Tutorials Point.',
index: 29,
input: 'hello how are you welcome to <b> Tutorials Point.</b>' ]
heregex
The complex regular expressions we write using the syntax provided by JavaScript are
unreadable, therefore to make Regular expressions more readable, CoffeeScript provides an
extended syntax for regular expressions known as heregex. Using this syntax, we can break the
normal regular expressions using whitespaces and we can also use comments in these extended
regular expressions, thus making them more user friendly.
Example
The following example demonstrates the usage of the advanced regular expressions in
CoffeeScript heregex. In here, we are rewriting the above example using the advanced regular
expressions. Save this code in a file with name heregex_example.coffee
Open the command prompt and compile the .coffee file as shown below.
228
CoffeeScript
result = heregex.exec(input_data);
console.log(result);
}).call(this);
Now, open the command prompt again and run the CoffeeScript file as shown below.
[ '<b>Tutorials Point.</b>',
'Tutorials Point.',
index: 29,
input: 'hello how are you welcome to <b>Tutorials Point.</b>' ]
229
21. CoffeeScript – Classes and Inheritance CoffeeScript
JavaScript does not provide the class keyword. We can achieve inheritance in JavaScript using
objects and their prototypes. Every object have their own prototype and they inherit functions
and properties from their prototypes. Since the prototype is also an object, it also has its own
prototype.
Though the prototypal inheritance is far more powerful than classic inheritance, it is difficult and
confusing for novice users.
Classes in CoffeeScript
Addressing to this problem, CoffeeScript provides a basic structure known as class which is built
using the JavaScript's prototypes. You can define a class in CoffeeScript using the class keyword
as shown below.
class Class_Name
Example
Consider the following example, here we have created a class named Student using the
keyword class.
class Student
If you compile the above code, it will generate the following JavaScript.
var Student;
Student = (function() {
function Student() {}
return Student;
})();
Instantiating a class
We can instantiate a class using the new operator just like other object oriented programming
languages as shown below.
new Class_Name
230
CoffeeScript
Example
You can instantiate the above created (Student) class using the new operator as shown below.
class Student
new Student
If you compile the above code, it will generate the following JavaScript.
var Student;
Student = (function() {
function Student() {}
return Student;
})();
new Student;
Defining a Constructor
A constructor is a function that is invoked when we instantiate a class, its main purpose is to
initialize the instance variables. In CoffeeScript, you can define a constructor just by creating a
function with name the constructor as shown below.
class Student
constructor: (name)->
@name = name
In here, we have defined a constructor and assigned the local variable name to the instance
variable. The @ operator is an alias to the this keyword, it is used to point the instance variables
of a class.
If we place @ before an argument of the constructor, then it will be set as an instance variable
automatically. Therefore, the above code can be written simply as shown below −
class Student
constructor: (@name)->
Example
Here is an example of a constructor in CoffeeScript. Save it in a file with the name
constructor_example.coffee
231
CoffeeScript
#Defining a class
class Student
constructor: (@name)->
c:\>coffee -c constructor_example.coffee
Student = (function() {
function Student(name) {
this.name = name;
}
return Student;
})();
}).call(this);
coffee constructor_example.coffee
232
CoffeeScript
Instance Properties
Same as in objects, we can also have properties within a class. And these are known as instance
properties.
Example
Consider the following example. In here, we have created variables (name, age) and a function
(message()) within the class and accessed them using its object. Save this example in a file
named instance_properties_example.coffee
#Defining a class
class Student
name="Ravi"
age=24
message: ->
"Hello "+name+" how are you"
Student = (function() {
var age, name;
function Student() {}
name = "Ravi";
age = 24;
Student.prototype.message = function() {
233
CoffeeScript
return Student;
})();
console.log(student.message());
}).call(this);
Static Properties
We can define static properties in the class. The scope of the static properties is restricted within
the class and we create static functions using the this keyword or its alias @ symbol and we have
to access these properties using the class name as Class_Name.property.
Example
In the following example, we have created a static function named message. and accessed it.
Save it in a file with the name static_properties_example.coffee.
#Defining a class
class Student
@message:(name) ->
"Hello "+name+" how are you"
console.log Student.message("Raju")
Open the command prompt and compile the above CoffeeScript file using the following
command.
c:\>coffee -c static_properties_example.coffee
Student = (function() {
function Student() {}
234
CoffeeScript
Student.message = function(name) {
return "Hello " + name + " how are you";
};
return Student;
})();
console.log(Student.message("Raju"));
}).call(this);
c:\>coffee static_properties_example.coffee
Inheritance
In CoffeeScript, we can inherit the properties of one class in another class using extends
keyword.
Example
Following is an Example of inheritance in CoffeeScript. In here, we have two classes namely
Add and My_class. We inherited the properties of class named Add in the class My_class, and
accessed them using the extends keyword.
#Defining a class
class Add
a=20;b=30
addition:->
console.log "Sum of the two numbers is :"+(a+b)
235
CoffeeScript
my_class.addition()
CoffeeScript uses prototypal inheritance behind the scenes. In CoffeeScript, whenever we create
instances, the parent class's constructor is invoked until we override it.
We can invoke the constructor of the parent class from the subclass, using the super() keyword
as shown in the example given below.
#Defining a class
class Add
constructor:(@a,@b) ->
addition:=>
console.log "Sum of the two numbers is :"+(@a+@b)
multiplication:->
console.log "Product of the two numbers is :"+(@a*@b)
Dynamic Classes
CoffeeScript uses prototypal inheritance to automatically inherit all of a class's instance
properties. This ensures that classes are dynamic; even if you add properties to a parent class
after a child has been created, the property will still be propagated to all of its inherited children.
class Animal
constructor: (@name) ->
Animal::rip = true
236
CoffeeScript
237
22. CoffeeScript – Ajax CoffeeScript
AJAX stands for Asynchronous JavaScript and XML. It is a new technique for creating
better, faster, and more interactive web applications with the help of XML, HTML, CSS,
and Java Script.
Ajax uses XHTML for content, CSS for presentation, along with Document Object Model
and JavaScript for dynamic content display.
Conventional web applications transmit information to and from the server using
synchronous requests. It means you fill out a form, hit submit, and get directed to a new
page with new information from the server.
With AJAX, when you hit submit, JavaScript will make a request to the server, interpret
the results, and update the current screen. In the purest sense, the user would never
know that anything was even transmitted to the server.
XML is commonly used as the format for receiving server data, although any format,
including plain text, can be used.
A user can continue to use the application while the client program requests information
from the server in the background.
In general, we use jQuery to work with Ajax. Following is an example of Ajax and jQuery
<html>
<head>
<title>The jQuery Example</title>
<script type = "text/javascript"
src =
"http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
238
CoffeeScript
<body>
</body>
</html>
Here load() initiates an Ajax request to the specified URL /coffeescript/result.html file. After
loading this file, all the content would be populated inside <div> tagged with ID stage. Assuming
that our /jquery/result.html file has just one HTML line −
<h1>THIS IS RESULT...</h1>
When you click the given button, then result.html file gets loaded.
<html>
<head>
<title>The jQuery Example</title>
<script type = "text/javascript"
src =
"http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="http://coffeescript.org/extras/coffee-script.js"></script>
<script type="text/coffeescript">
$(document).ready ->
$('#driver').click (event) ->
$('#stage').load '/jquery/result.html'
239
CoffeeScript
return
return
</script>
</head>
<body>
</body>
</html>
240
23. CoffeeScript – jQuery CoffeeScript
jQuery is a fast and concise library/framework built using JavaScript created by John Resig in
2006 with a nice motto − Write less, do more.
jQuery simplifies HTML document traversing, event handling, animating, and Ajax interactions
for rapid web development. Visit our jQuery tutorial to know about jQuery.
We can also use CoffeeScript to work with jQuery. This chapter teaches you how to use
CoffeeScript to work with jQuery.
Keep the following points in mind while converting the to be while using jQuery with CoffeeScript.
The $ symbol indicates the jQuery code in our application. Use this to separate the jQuery code
from the scripting language as shown below.
$(document).ready
There is no need of using braces in in CoffeeScript except while calling the functions with
parameters and dealing with the ambiguous code and we have to replace the function
definition function() with an arrow mark as shown below.
$(document).ready ->
Remove the unnecessary return statements, since CoffeeScript implicitly returns the tailing
statements of a function.
Example
Following is an JavaScript code where <div> elements are being inserted just before the clicked
element −
<html>
<head>
<title>The jQuery Example</title>
<script type = "text/javascript"
src =
"http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
$(this).before('<div class="div"></div>' );
});
});
</script>
<style>
.div{ margin:10px;padding:12px; border:2px solid #666; width:60px;}
</style>
</head>
<body>
</body>
</html>
Now, we can convert the above code into CoffeeScript code as shown below
<html>
<head>
<title>The jQuery Example</title>
<script type = "text/javascript" src =
"http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="http://coffeescript.org/extras/coffee-script.js"></script>
<script type="text/coffeescript">
$(document).ready ->
$('div').click ->
$(this).before '<div class="div"></div>'
return
242
CoffeeScript
return
</script>
<style>
.div{ margin:10px;padding:12px; border:2px solid #666; width:60px;}
</style>
</head>
<body>
</body>
</html>
What is Callback?
Callback is an asynchronous equivalent for a function. A callback function is called at the
completion of a given task. Node makes heavy use of callbacks. All APIs of Node are written is
such a way that they supports callbacks.
For example, a function to read a file may start reading file and return the control to execution
environment immidiately so that next instruction can be executed. Once file I/O is complete, it
243
CoffeeScript
will call the callback function while passing the callback function, the content of the file as
parameter. So there is no blocking or wait for File I/O. This makes Node.js highly scalable, as it
can process high number of request without waiting for any function to return result.
var fs = require("fs");
console.log(data.toString());
console.log("Program Ended");
$ node main.js
var fs = require("fs");
244
CoffeeScript
console.log("Program Ended");
$ node main.js
Program Ended
Tutorials Point is giving self learning content
to teach the world in simple and easy way!!!!!
These two examples explain the concept of blocking and non-blocking calls. The first example
shows that the program blocks until it reads the file and then only, it proceeds to end the
program, whereas in the second example, the program does not wait for file reading but it just
proceeded to print "Program Ended".
Thus, a blocking program executes very much in sequence. From programming point of view,
its easier to implement the logic but non-blocking programs do not execute in sequence. In case
a program needs to use any data to be processed, it should be kept within the same block to
make it sequential execution.
245
24. CoffeeScript – MangoDB CoffeeScript
MongoDB is a cross-platform, document oriented database that provides, high performance, high
availability, and easy scalability. MongoDB works on concept of collection and document. For
more information read our MongoDB Tutorial.
In this chapter you will learn how to communicate with MongoDB database using CoffeeScript.
Installation
The MongoDB database can be integrated with CoffeeScript using Node.js 2.0 driver of
MongoDB. First of all you need to install MongoDB in your system, by referring
theenvironment chapter of our MangoDB tutorial.
After installing MangoDB successfully browse through its bin folder (if you haven't set the path)
and start the MangoDB service as shown below.
Finally install MangoDB driver and it's dependencies by executing the following NPM command
in the command prompt.
Connecting to MangoDB
In order to connect to MongoDB, first of all create MongoClient using this, invoke
theconnect() function. This function accepts url, and a callback function as parameters.
Following CoffeeScript code shows how to connect to MongoDB server. If the MongoDB server is
running in your system this program establishes a connection to the server.
246
CoffeeScript
Save the above code in a file with name connect_db.coffee and execute it as shown below. If
database is successfully created then it will give following message
Creating a Collection
A collection in MongoDB holds the documents we store in it. You can create a collection by using
the collection() function. This function accepts a string argument that represents the name of
the collection we want to create.
Following CoffeeScript code shows how to create a collection in MongoDB. In case of any errors,
they will be displayed on the console.
#Create collection
247
CoffeeScript
col = db.collection('My_collection')
console.log "Collection created successfully."
#Close connection
db.close()
return
Save the above code in a file with name create_collection.coffee and execute it as shown below.
If the collection is created successfully then it will give following message
c:/>
coffee create_collection.coffee
Connection established to mongodb://localhost:27017/testdb
Collection created successfully.
Inserting Documents
You can inset documents in to a collection in MangoDB you need to invoke a function
named insert() by passing the list of documents that are needed to be inserted, as parameters.
248
CoffeeScript
#Inserting documents
col.insert [doc1,doc2,doc3], (err, result) ->
if err
console.log err
else
console.log "Documents inserted successfully"
#Close connection
db.close()
return
return
Save the above code in a file with name insert_documents.coffee and execute it as shown below.
If the documents are inserted successfully then it gives following message
c:/>
coffee insert_documents.coffee
Connection established to mongodb://localhost:27017/testdb
Documents inserted successfully
Reading Documents
You can retrieve the documents that are stored in MongoDB using a function named find(). The
following CoffeeScript code shows how to retrieve the records that are stored in MangoDB.
249
CoffeeScript
Save the above code in a file with name read_documents.coffee and execute it as shown below.
This programs retrieves the required document in the specified collection and displays it as
shown below.
You can also read all the documents existing in a particular collection by executing
thefind() function with out passing any arguments to it as shown below.
url = 'mongodb://localhost:27017/testdb'
Save the above code in a file with name read_all_documents.coffee and execute it as shown
below. this programs retrieves all the documents in the specified collection and displays it as
shown below.
251
CoffeeScript
city: 'Mumbai' } ]
Updating Documents
You can update the documents that are stored in MongoDB using a function
namedupdate(). Following CoffeeScript code shows how to update the records that are stored in
MangoDB.
#Closing connection
db.close()
return
return
This program updates the city of the employee named Ram from Hyderabad to Delhi.
Save the above code in a file with name update_documents.coffee and execute it as shown
below. this programs retrieves the documents in the specified collection and displays it as shown
below.
252
CoffeeScript
After updating, if you execute the read_documents.coffee program, then you will observe that
the city name of the person named Ram is updated from Hyderabad to Delhi.
Deleting Documents
You can delete all the documents from the collection using the remove() function. Following
CoffeeScript code shows how to delete all the records that are stored in MangoDB.
#Creating collection
col = db.collection('My_collection')
#Deleting Data
col.remove()
console.log "Document deleted"
253
CoffeeScript
#Closing connection
db.close()
return
Save the above code in a file with name delete_documents.coffee and execute it as shown below.
this programs removes all the documents in the specified collection displaying the following
messages.
After deleting, if you execute the read_documents.coffee program, then you will get an empty
collection as shown below.
254
25. CoffeeScript – SQLite CoffeeScript
Unlike many other database management systems, SQLite is not a client–server database
engine. For more information read our SQLite Tutorial
In this chapter you will learn how to communicate with SQLite database using CoffeeScript.
Installation
The SQLite3 database can be integrated with CoffeeScript using node-sqlite3 module. This
module works with Node.js v0.10.x, v0.12.x, v4.x, and v5.x. This module caters various
functions to communicate with SQLite3 using CoffeeScript, in addition to this it also provides an
Straightforward query and parameter binding interface, and an Query serialization API.
You can install the node-sqlite3 module using npm as shown below.
To use sqlite3 module, you must first create a connection object that represents the database
and this object will help you in executing all the SQL statements.
Connecting to Database
In order to connect to SQLite database first of all create an its package by invoking the
require() function of the node-sqlite3 module and pass the string sqlite3 as a parameter to
it. Then connect to a database by passing the name of the database to
sqlite3.Database() construct.
Following CoffeeScript code shows how to connect to an existing database. If database does not
exist, then it will be created with the given name test.db, opened and finally the database object
will be returned.
We can also supply :memory: to create an anonymous in-memory database and, an empty string
to create anonymous disk-based database, instead of test.db. Save the above code in a file with
name create_db.coffee and execute it as shown below. If the database is successfully created,
then it will produce the following message –
255
CoffeeScript
Creating a Table
You can create a table in SQLite database through CoffeeScript using the run() function. Pass
the query to create a table to this function in String format.
The following CoffeeScript program will be used to create a table in previously test.db database
−
db.serialize ->
db.run 'CREATE TABLE STUDENT (name TEXT, age INTEGER, city TEXT)'
console.log "Table created successfully"
return
db.close()
The serialize() function sets the database in serialized mode. In this mode when ever a callback
encounters, it will be called immediately. The quires in that callback are executes serially. Soon
the function returns The database will be set to normal mode again. After completing the
transaction we need to close the connection using close() function.
Save the above code in a file with name create_table.coffee and execute it as shown below.
This will create a table named STUDENT in the database test.db displaying the following
messages.
It also accepts query with bind variables (?), values to these variables can be attached using
run() function. You can insert multiple records using prepared statement, and after inserting all
the records, you need to finalize the prepared statement using finalize() function.
256
CoffeeScript
The following CoffeeScript program shows how to insert records in the table named STUDENT
created in previous example.
db.serialize ->
stmt = db.prepare('INSERT INTO STUDENT VALUES (?,?,?)')
stmt.run 'Ram',24,'Hyderabad'
stmt.run 'Robert',25,'Mumbai'
stmt.run 'Rahim',26,'Bangalore'
stmt.finalize()
console.log "Data inserted successfully"
return
db.close()
Save the above code in a file with name insert_data.coffee and execute it as shown below. This
will populate the table named STUDENT displaying the following messages.
The following CoffeeScript program shows how we can fetch and display records from the table
named STUDENT created in the previous example
257
CoffeeScript
db.serialize ->
console.log "The contents of the table STUDENT are ::"
db.each 'SELECT rowid AS id, name,age,city FROM STUDENT', (err, row) ->
console.log row.id + ': ' +row.name+', '+ row.age+', '+ row.city
return
return
db.close()
Save the above code in a file with name retrive_data.coffee and execute it as shown below. This
retrieves all the records in the table named STUDENT and displays on the console as follows.
Updating Data
The following CoffeeScript code shows how we can use UPDATE statement to update any record
and then fetch and display updated records in the table named STUDENT
db.serialize ->
#Updating data
stmt = db.prepare('UPDATE STUDENT SET city = ? where name = ?')
stmt.run 'Delhi','Ram'
console.log "Table updated"
stmt.finalize()
258
CoffeeScript
console.log "The contents of the table STUDENT after update operation are ::"
db.each 'SELECT rowid AS id, name, city FROM STUDENT', (err, row) ->
console.log row.id + ': ' +row.name+', '+ row.city
return
return
db.close()
Save the above code in a file with name update_data.coffee and execute it as shown below. This
updates the city of the student named ram and displays all the records in the table after update
operation as follows.
Deleting Data
The following CoffeeScript code shows how we can use DELETE statement to delete any record
and then fetch and display remaining records from the table named STUDENT.
db.serialize ->
#Deleting data
stmt = db.prepare('DELETE FROM STUDENT WHERE name = ?')
stmt.run 'Ram'
console.log "Record deleted"
stmt.finalize()
console.log "The contents of the table STUDENT after delete operation are ::"
db.each 'SELECT rowid AS id, name, city FROM STUDENT', (err, row) ->
console.log row.id + ': ' +row.name+', '+ row.city
return
return
db.close()
Save the above code in a file with name delete_data.coffee and execute it as shown below. It
deletes the record of the student named ram and displays all the remaining in the table after
delete operation as follows.
Successfully connected
Record deleted
The contents of the table STUDENT after delete operation are ::
2: Robert, Mumbai
3: Rahim, Bangalore
260