You are on page 1of 66

What You Need to Know

about JavaScript

Delve into the fundamentals of JavaScript

Gabriel Cnepa

BIRMINGHAM - MUMBAI
What you need to know about JavaScript

Copyright 2016 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval
system, or transmitted in any form or by any means, without the prior written
permission of the publisher, except in the case of brief quotations embedded in
critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy
of the information presented. However, the information contained in this book is
sold without warranty, either express or implied. Neither the author, nor Packt
Publishing, and its dealers and distributors will be held liable for any damages
caused or alleged to be caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the
companies and products mentioned in this book by the appropriate use of capitals.
However, Packt Publishing cannot guarantee the accuracy of this information.

First Published: May 2016

Production reference: 1300516

Published by Packt Publishing Ltd.


Livery Place
35 Livery Street
Birmingham B3 2PB, UK.
www.packtpub.com
About the Author

Gabriel Cnepa is a Linux foundation certified system administrator


(LFCS-1500-0576-0100) and web developer from Villa Mercedes, San Luis,
Argentina. He works for a multinational consumer goods company and takes
great pleasure in using FOSS tools to increase productivity in all areas of his
daily work. When he's not typing commands or writing code or articles, he
enjoys telling bedtime stories with his wife to his two little daughters and
playing with them, which is a great pleasure of his life.
About the Reviewer

Walter Molina is a web developer from Villa Mercedes, San Luis, Argentina. His
skills include, but they are not limited to, HTML5, CSS3, and JavaScript. He uses these
technologies at a Jedi/ninja level (along with a plethora of JavaScript libraries) in his
daily work as frontend developer for a prestigious software firm. He holds a bachelor's
degree in computer science and is co-founder of Tachuso (www.tachuso.com), a social
media and design agency. He is also a member of the CS department at a local college,
where he teaches programming skills to second and third year students.
www.PacktPub.com

Support files, eBooks, discount offers, and more


At www.PacktPub.com, you can also read a collection of free technical articles,
sign up for a range of free newsletters and receive exclusive discounts and offers
on Packt books, eBooks, and videos.
TM

https://www.packtpub.com/books/subscription/packtlib

Do you need instant solutions to your IT questions? PacktLib is Packt's online


digital book library. Here, you can access, read and search across Packt's entire
library of books.

Why subscribe?
Fully searchable across every book published by Packt
Copy and paste, print and bookmark content
On demand and accessible via web browser

Free access for Packt account holders


If you have an account with Packt at www.PacktPub.com, you can use this to access
PacktLib today and view nine entirely free books. Simply use your login credentials
for immediate access.
Table of Contents
What is JavaScript? 1
Variables, mathematical operations, and string concatenation 1
Arrays and objects 5
Conditionals and loops 6
Functions 8
Libraries 9
Getting Started with ECMAScript 6 12
Template strings 13
Tagged templates 15
Arrow functions 16
Classes 19
The let keyword 22
Bringing It All Together with Visual Studio Code 24
Choosing an integrated development environment 24
Creating directories and files for our web application with
Visual Studio Code 25
Writing JavaScript code for our application 32
Testing our application 37
To the Future and Beyond 40
What's in the near future of JavaScript? 40
JavaScript Cheat Sheet 44
Reviewing the number object 44
Working with strings 45
Boolean object fundamentals 46
Grouping statements into functions 47
Getting started with arrays 48
Fundamentals of date objects 49

[i]
Table of Contents

Introducing assignment and arithmetic operators 50


Using comparison operators 51
Several possible courses of action Using the switch-case
control structure 52
Summary 53
What to do next? 54
Broaden your horizons with Packt 54

[ ii ]
Preface

What you need to know


about JavaScript
This eGuide is designed to act as a brief, practical introduction to JavaScript. It is
full of practical examples which will get you up and running quickly with the core
tasks of JavaScript.

We assume that you know a bit about what JavaScript is, what it does, and why you
want to use it, so this eGuide won't give you a history lesson in the background of
JavaScript. What this eGuide will give you, however, is a greater understanding of
the key basics of JavaScript so that you have a good idea of how to advance after
you've read the guide. We can then point you in the right direction for what to learn
next after giving you the basic knowledge to do so.

What You Need to Know about JavaScript will do the following:

Cover the fundamentals and the things you really need to know, rather than
niche or specialized areas
Assume that you come from a fairly technical background and so understand
what the technology is and what it broadly does
Focus on what things are and how they work
Include practical examples to get you up, running, and productive quickly

[ iii ]
Preface

Overview
In this eGuide, we will review the fundamental concepts behind JavaScript, which
is the most used language among frontend developers and web designers. It is also
highly used among backend and fullstack developers (according to https://www.
packtpub.com/skillup/web-dev-salary-report). Besides being easy to learn,
JavaScript is used everywhere on the web today. This, in itself, I believe is enough
reason to either learn the language or polish your existing JavaScript skills.

JavaScript is present the moment you launch your web browser to visit your favorite
pages and interact with them; this applies to the end users of your applications. As a
web developer, here are some common uses of JavaScript:

If you need to create a contact form where some fields are required, you can
rely on JavaScript to alert the user if he has missed some of these fields and
to validate or sanitize their contents. You don't have to rely on alert windows
anymore as the Document Object Model (DOM) can be accessed through
JavaScript to manipulate its look, content, and attributes.
You can populate search boxes with common terms as you type into them;
this is a feature known as autocomplete.
Displaying or hiding information on demand and animating elements on a
page is a walk in the park using JavaScript.
Using JavaScript, you can pass requests to a backend server and handle
responses without reloading the page.
And many more

All of this goes to show that the mission of JavaScript is to bring websites to life and
to enrich user experience while making things easier and keeping the design of web
pages beautiful.

Please join us as we dive into this powerful language in this eGuide.

[ iv ]
What you need to know about JavaScript

What is JavaScript?
JavaScript is a very versatile language because it supports both object-oriented and
procedural programming to bring interactivity to a Web page. On top of this, due
to its flexibility, it allowed developers to write several wellknown tools (also known
as libraries, which we will discuss near the end of this section) that provide robust
solutions with little extra effort. Under the hood, these libraries are a combination of
variable declarations, arithmetic, and conditional operators, iteration loops, functions,
and event responses. The purpose of this section is to help you get up to speed with
some JavaScript fundamentals, and briefly refresh your mind on these constructing
blocks of the language up to ECMAScript version 5. Then, you will be in better shape
to tackle ECMAScript 6 and its new features in the next section.

Variables, mathematical operations,


and string concatenation
Like other programming languages, JavaScript enforces some rules on variable
naming. For example, a valid variable name cannot start with a number (although
numbers are allowed inside a variable name), it cannot contain spaces, arithmetic,
Boolean operators, or punctuation signs. In addition to this, you can't use reserved
keywords and must avoidto the extent possibleusing mixed cases because variable
names in JavaScript are case-sensitive; myCar and MyCar represent different variables.

Reserved keywords that cannot be used as variable names (which are also known
as identifiers) are listed in section 11.2.6.1 of the ECMAScript 6 specification, which
is available in HTML format at http://www.ecma-international.org/ecma-
262/6.0/ and in PDF format at http://www.ecma-international.org/ecma-
262/6.0/ECMA-262.pdf.

[1]
What you need to know about JavaScript

A variable can be declared and given a value in two separate steps, which are
displayed as follows:
var myTeam;
myTeam = 'Chicago Bulls';

They can also be given a value in a single step, as follows:


var myTeam = 'Chicago Bulls';

JavaScript allows us to declare variables without the var keyword (the variable will
be global). Anyway, this practice is not recommended, and most developers will
advise against it and think that it should be deprecated.

Then, this can be queried by simply calling the variable by name, as follows:
myTeam;

Then, this can be changed by assigning a different value, as follows:


myTeam = 'Indiana Pacers';

The preceding steps are illustrated in the following figure inside a Firefox developer
console (which can be accessed through the Ctrl + Shift + K key combination). If you
use Google Chrome, you can access the Chrome developer tools with Ctrl + Shift + J
instead:

Initializing and calling variables

After typing the var myTeam = 'Chicago Bulls'; statement, as shown in the
preceding figure and pressing Enter, undefined is returned because an assignment
does not produce a value. On the other hand, when the value of myTeam is queried
through an expression, its value is returned as a string type.

[2]
What you need to know about JavaScript

Also, mathematical expressions, such as 3*4;, produce a value, which is printed to the
console. However, their result can be assigned to variables and used in operations
later, as seen in the following figure:

Mathematical operations with variables

You can also concatenate the values of two or more variables of different types to
form a new variable or produce new output using the + sign:
var sumResult = 'The sum of ' + firstNumber + ' and ' +
secondNumber + ' equals ' + sum;
sumResult;

When building a string variable as the result of the concatenation of two or more
values, it is recommended that you be consistent with the use of single or double
quotes. Many JavaScript developers prefer to use double quotes to enclose string
values as this allows you to use single quotes within the variable without the need
to escape them.

While others prefer to use single quotes, the principle that should be followed is this:
if you need to use one form of quote in the string, you might want to use the other
one as the literal.

[3]
What you need to know about JavaScript

These concepts are displayed in the following figure:

Using single and double quotes in string variables

In other words, you can perform the following:


var nickName1 = "I'm a programmer and my nickname is 'Geek' for
that reason";

This can be used instead of the following:


var nickName2 = 'I\'m a programmer and my nickname is \'Geek\' for
that reason';

Or, you can also use this:


var nickName3 = 'I\'m a programmer and my nickname is "Geek" for
that reason';

The bottom line is: you pick your poison! Just don't forget to be consistent.

[4]
What you need to know about JavaScript

Arrays and objects


An array is a collection of values (different types are allowed) that can be saved into
a single variable. This structure must be enclosed within square brackets and each
element is referenced using a zero-based index notation. For example, take a look
at the following:
var rockBands= ['The Beatles', 'Rolling Stones', 'Pink Floyd'];

As is the case with other variables, you can query the value of rockBands, as follows:
rockBands;

Additionally, you can retrieve the value of a specific item in rockBands like
the following:
rockBands[0];

Or, you can also use the following:


rockBands[2];

This example is illustrated in the following figure:

Initializing array variables and retrieving elements

Going one step further, you can easily create an object variable with properties.
Using this approach, you can think of an object as a thing. For example, let's create an
object variable named dog with three properties: color, age, and breed, as follows:
var dog= {color: 'Brown', age: 4, breed: 'Boxer'};

[5]
What you need to know about JavaScript

You can then query the object variable as a whole or each property using the dot
notation (the object name followed by a dot and the property name):
dog;
dog.color;
dog.age;
dog.breed;

Properties cannot only be fixed values, but they can also be methods that represent
an action that is associated with the object. Using the dog object, let's redefine it and
add a method property called bark:
var dog= {color: 'Brown', age: 4, breed: 'Boxer', bark: function()
{console.log('Guau guau')}};

A method property can be invoked like a regular property as explained previously,


and then followed by a set of parentheses that denote an action:
dog.bark();

This example is shown in the following figure:

Initializing and querying objects with properties and methods

Likewise, you can store HTML elements in object variables, as we will show you in
the example near the end of this chapter.

Conditionals and loops


In JavaScript, you can build a condition test using the usual ifelse block and the
identity operator (===). In the following example, we will use the console.log()
method to display its parameter to the web console:
var myNumber = 4;
if (myNumber === 5) {

[6]
What you need to know about JavaScript

console.log('The number is equal to five');


}
else {
console.log('The number is NOT equal to five');
}

To illustrate a basic for loop, let's consider the rockBands array variable used
earlier, as follows:
for (var i = 0; i < rockBands.length; i++) {
console.log('Band #' + i + ' is ' + rockBands[i]);
}

In the preceding example, we iterate over the rockBands array using the i number
variable as an index. Finally, we send a different line to the web console in each
iteration. The result is shown in the following figure:

Using conditionals to control flow and loops to repeat actions

[7]
What you need to know about JavaScript

Another way of displaying the same information is using a do...while loop,


which executes the indicated action as long as the condition in the while clause
evaluates to true:
var i = 0;
do {
console.log('Band #' + i + ' is ' + rockBands[i]);
i++;
} while (i < rockBands.length);

You will use conditionals and loops in your JavaScript programs when you need to
take decisions that are based on the values of variables and when you need to repeat
a similar action a given number of times, respectively. Objects will come in handy
when you need to define complex structures with properties and methods instead
of mere lists of items (for which you will want to use an array variable).

Functions
When we defined the dog object previously, we used a function as a method
property (bark) to indicate an action that is associated with the object. Thus, you
can think of a JavaScript function as a procedure that performs a task, manipulates
variables, and calculates a result.

A function declaration consists of the keyword function, followed by the name of the
function, a list of optional arguments to be passed to the function (if there are more
than one, they should be separated by commas), and a list of one or more JavaScript
statements enclosed in curly brackets.

For example, we can define a function named sum that takes two numbers
(firstNumber and secondNumber, to use the same variables as before) and returns the
sum of these numbers. Function naming is another area where effective developers
use one pattern or another: some prefer to use all lowercase letters (for example, sum),
while others like to use uppercase at the beginning of the name (Sum).

Again, either method works fine, but you are strongly advised to choose one and
stick with it to avoid confusion down the road. Either way, it would be a good idea
to check out http://www.w3schools.com/js/js_conventions.asp for current
naming conventions.
function sum(firstNumber,secondNumber) {
var mySum = firstNumber + secondNumber;
return 'The sum of ' + firstNumber + ' and ' + secondNumber + '
equals ' + mySum;
}

[8]
What you need to know about JavaScript

Thus, we don't need to redefine firstNumber and secondNumber each time we want
to add two values. We can just call the function with different arguments and that's
all that there is to it, as seen in in the following figure:

Defining and calling functions

After reviewing the essential concepts of variables, operations, arrays, objects,


conditionals, loops, and functions, we are ready to put it all together into libraries,
as we will explain next.

Libraries
In order to provide more complex functionality with little extra effort, you can
combine JavaScript statements and functions into a single file that is invoked in
a web page. These files use the .js (for JavaScript) extension, and they are called
libraries.

Although there are several popular JavaScript libraries (such as jQuery, ReactJS,
and the Dojo Toolkit to name a few examples), you can write your own! Let's see
how to do this.

Save the following code into a file named test.js:


/* Function declaration
====================

The SayHi project requires 3 parameters: your name, age, and profession
(in that order).

[9]
What you need to know about JavaScript

In the function definition, these three parameters are named a, b, and c.

The function returns a greeting using these values:


*/
function SayHi(a,b,c){
var person = {name: a, age: b, profession: c};
return 'My name is ' + person.name + ' and am ' + person.age + '
years old. I am a ' + person.profession + '.';
}

/* Object definition
=================

The introducingMyself object is an object variable that gets the first h3 element
in the document. This element has a property called textContent where we will
display the result of calling SayHi with the following indicated parameters:
*/
var introducingMyself = document.querySelector('h3');
introducingMyself.textContent = SayHi('Gabriel', 33,
'programmer');

We will then create a file named index.html in the same directory where you saved
test.js. Note that, in order to reference the external file test.js, you need to place
the reference inside <script> tags as indicated in the following:
<!DOCTYPE html>
<html lang = "en-US">
<head>
<meta charset = "UTF-8">
<title>Chapter 1</title>
</head>
<body>
<h1>First example</h1>
<h3></h3>
<script src="test.js"></script>
</body>
</html>

Some developers place the reference to the .js file inside the head section so that
any function in this file would be available before the document finishes loading,
while others prefer to place it right before the closing </body> tag to favor load
speeds. Although this is a matter of personal preference, the former method is the
recommended practice.

[ 10 ]
What you need to know about JavaScript

Save both files and open index.html with your web browser. To change the text
inside the <h3> tags, simply pass different parameters to the SayHi function inside
test.js and save the changes. The result should be similar to the following figure:

In the real world, it is not practical to edit a JavaScript library each time you want
to change the content of a HTML element. To do this, you would typically rely on
HTML controls (such as text boxes and buttons) and use the JavaScript to handle
things that require some form of logic. The preceding example, while basic and not
very useful, is effective to illustrate the way JavaScript statements can be saved into
a file that can be referenced and utilized on the HTML side.

You can find the code for this example at https://github.com/gacanepa/


javascript-exercises. Alternatively, this working example is available at
https://jsfiddle.net/gacanepa/0yswLco6/.

[ 11 ]
What you need to know about JavaScript

Getting Started with


ECMAScript 6
In the previous section, we reviewed the history of JavaScript and gave you a brief
mind-refresher of several fundamental programming concepts as applied up until
ECMAScript 5, the version which all web developers worldwide are familiar with
and most web browsers are compatible with.

As we also mentioned earlier, the latest specification of JavaScript is ECMAScript 6,


which has new features and functionality. In this section, we will explain what
these features are, and where and how you would like to consider using them in
an application. After going through this section, you should also be able to write
cleaner and more powerful JavaScript codecompared to previous versions of
the languageto implement the same functionality.

Before we dive into ECMAScript 6, it is important to check the compatibility of


our preferred web browser with the new features of the language. In the following
GitHub blog (http://kangax.github.io/compat-table/es6/), you will be able
to find a table that lists ECMAScript 6 features and compatibility with major modern
web browsers.

To perform the exercises and demonstrations in this section, you can


use any text editor that you feel comfortable with. Notepad++ in
Windows and Gedit/Pluma in Linux are only some examples that we
will use here, but feel free to use something else. Additionally, we can
use Codepen (http://codepen.io) or ES6 Fiddle (http://www.
es6fiddle.net/); both are online services that allow us to test the
code snippets we will present herealong with the Firefox web console,
as we did in the previous section. Additionally, you can find the files
with the code in https://github.com/gacanepa/javascript-
exercises, and the complete working examples in these files.

[ 12 ]
What you need to know about JavaScript

That said, let's get started.

Template strings
Template strings introduce several features that solve limitations in regular
JavaScript strings. For example, let's consider the case of a multiline string in
ECMAScript 5, which produces a SyntaxError: unterminated string
literal message when you execute it:

var greeting = "Hi! This


is a wonderful day, isn't it?";

To avoid this, in ECMAScript 5 you would use backslashes, as follows:


var greeting = "Hi! This \
is a wonderful day, isn't it?";

In ECMAScript 6, you can write much cleaner code:


var greeting = `Hi! This
is a wonderful day, isn't it?`;

Both methods are illustrated in the following figure:

Multiline strings in ECMAScript 5 and 6

[ 13 ]
What you need to know about JavaScript

Another advantage of template strings consists of string interpolation (also known as


string substitution). What you would do with one or more string concatenations and
several objects with property methods, you can do more easily with template strings
and substitution.

For example, let's define an object variable named person, as follows:


var person = {name: "Gabriel", age: "33", profession: "developer",
saySomething: function msg(d){return "This is my message: " + d}};

With ECMAScript 5, the following line returns a personal presentation:


console.log("My name is " + person.name + " and I'm a " +
person.profession + ". " + person.saySomething("Happy Tuesday!"));

Whereas, in ECMAScript 6, template strings allow to output the same presentation


with the following:
console.log(`My name is ${person.name} and I'm a
${person.profession}. ${person.saySomething("Happy Tuesday!")}`);

This is much shorter and easier to read.

The preceding example is shown with more clarity in the following figure:

Comparing regular string concatenation with template string substitution

Using Template strings, you can enclose any JavaScript


expression inside ${}, not just variables. For example, if
you replace ${person.name} with ${person.name.
toUpperCase()}, the person's name will be printed
in uppercase, as indicated by the toUpperCase()
JavaScript function.

[ 14 ]
What you need to know about JavaScript

Tagged templates
Tagged templates represent an advanced form of template strings as they can tell
the difference between literals and values resulting from an operation or a JavaScript
expression, as shown earlier. In other words, tagged templates allow us to take
different actions on literals and values. An example will help us illustrate this feature.

In the following code snippet, namesToUpper is a function that is applied to the


template between backticks. The function definition takes two arrays (strings
and values) as parameters, which contain the literals and the values found in the
template, respectively:
function namesToUpper(strings, ...values) {
return strings.reduce(function test(a, b, c) {
return ${a}${values[c - 1].toUpperCase()}${b};
})
}
var fName = "Gabriel";
var mName = "Alejandro";
var lName = "Cnepa";
console.log(namesToUpper `First Name: ${fName}, Middle Name:
${mName}, Last Name: ${lName}`);

If you replace the return lines with two console.log() calls (one for each array),
the output should be shown in the following figure:

Applying a function to a tagged template

[ 15 ]
What you need to know about JavaScript

We can now use template strings to build a return value as per the code snippet that
we shared earlier. Note how, in the following figure, only the elements in the values
array are converted to uppercase.

Using tagged templates

In simple words, you can use tagged templates in any situation where you need to
follow different courses of action on literals and associated values. For example, you
can use tagged templates to sanitize input from a form. In this situation you certainly
want to prevent special characters from being passed to the backend application in
order to avoid a SQL injection or a cross-side scripting (XSS) attack.

Arrow functions
With arrow functions, you can obtain the same functionality as regular function
expressions but with shorter syntax. Additionally, arrow functions inherit the this
value from the enclosing context so that you don't need to use an extra variable to
pass an object from a parent function to an enclosed method.

To replace a regular function with an arrow method, enclose its parameters inside
parentheses and append the arrow notation (=>) followed by the JavaScript extension
inside curly brackets. In either case (parameter listing or expression definition), the
parentheses or curly brackets can be omitted if there is only one parameter or if the
expression consists of only one line.

With that in mind, let's rewrite the namesToUpper() function that we used earlier:
function namesToUpper(strings, ...values) {
return strings.reduce((a, b, c) => {
return `${a}${values[c - 1].toUpperCase()}${b}`;
})

[ 16 ]
What you need to know about JavaScript

}
var fName = "Gabriel";
var mName = "Alejandro";
var lName = "Cnepa";
console.log(namesToUpper `First Name: ${fName}, Middle Name:
${mName}, Last Name: ${lName}`);

As you can see in the following figure, the code still works as expected:

Using arrow functions to replace regular methods

For another example, let's define a Counter object and increment its value (starting at
0) by one each second until it reaches 5:

function Counter() {
this.value = 0;
var timer = setInterval(() => {
this.value++;
console.log(this.value);
if (this.value >= 5) {
clearInterval(timer);
}
}, 1000);
}
var p = new Counter();

Using arrow functions, this.value inside setInterval still refers to the Counter
object. Without arrow functions, this would switch to the global window object.
This can be observed using the following code snippet:
function Counter(){
this.value = 0;

[ 17 ]
What you need to know about JavaScript

var timer = setTimeout(function test() {


console.log(this);
}, 1000);
}
var p = new Counter();

The comparison between these two approaches (arrow functions versus regular
functions) and their corresponding effects on this inside a child method, is shown
in the following figure:

Scope of this using arrow functions vs. regular methods

As you can see, arrow functions simplify the code syntax, makes it much more
readable, and provide the same functionality with fewer lines.

[ 18 ]
What you need to know about JavaScript

Classes
Folks who are familiar with Object-Oriented Programming (OOP) have welcomed
this feature with open arms. Similarly to other programming languages, with
ECMAScript 6, you can now create objects with properties and methods using the
class keyword. This results, again, in code that is cleaner and easier to maintain.
ECMAScript 6 does this without creating a new OOP model in the language, but
uses a clearer syntax to handle objects and inheritance.

Up until ECMAScript 5, here's an example of what you would do to instantiate an


object of the individual type and to print a message to the console:
var individual = function Person(fName, lName, profession, age) {
// Properties
this.fName = fName;
this.lName = lName;
this.profession = profession;
this.age = age;
// Methods
this.saySomething = function (msg) {
console.log(msg + " I am a " + this.age + "-yr. old " +
this.profession );
};
}
var me = new individual("Gabriel", "Cnepa", "developer", "33");
console.log(me);
me.saySomething("What's up?");

The preceding code snippet gets the job done. However, let's see how we can
improve the code using a JavaScript class and other ECMAScript 6-specific features
that we have discussed previously:
class Person {
constructor(fName, lName, profession, age) {
// Properties
this.fName = fName;
this.lName = lName;
this.profession = profession;
this.age = age;
}
// Methods
saySomething() {
return `What's up? I am a ${this.age}-yr. old
${this.profession}`;
}
}
var me = new Person("Gabriel", "Cnepa", "developer", "33", 2500);
console.log(me.saySomething());

[ 19 ]
What you need to know about JavaScript

Both alternatives return the output shown in the following figure, but using classes
helps us write better and more understandable code:

Using classes to create objects

Another advantage that is associated with using classes to create and instantiate
objects is that we can also inherit from parent classes that may have some more
generic methods and properties. Building upon our previous example, let's add
a parent (also known as base) class named Employee with two generic properties
(hireDate and monthlySalary):
class Employee {
constructor(hireDate, monthlySalary) {
this.hireDate = hireDate;
this.monthlySalary = monthlySalary;
}
}

To have our Person class inherit from Employee, we will use the extends keyword
as follows:
class Person extends Employee

[ 20 ]
What you need to know about JavaScript

Properties available in Employee are made available to a Person object using the
super() function inside the constructor call. In addition to this, methods in the
parent class are available directly to the child object. In the following case, our
Person child class will inherit hireDate, monthlySalary, and getMonthlySalary()
(two properties and a method in the Employees class, respectively):
class Employee {
constructor(hireDate, monthlySalary) {
this.hireDate = hireDate;
this.monthlySalary = monthlySalary;
}
getMonthlySalary() {
return `I make ${this.monthlySalary} each month.`
}
}
class Person extends Employee {
constructor(fName, lName, profession, age, hireDate,
monthlySalary) {
// Properties
super(hireDate, monthlySalary);
this.fName = fName;
this.lName = lName;
this.profession = profession;
this.age = age;
}
// Methods
saySomething() {
return `What's up? I am a ${this.age}-yr. old ${this.profession}
and was hired on ${this.hireDate}.`;
}
}
var me = new Person("Gabriel", "Cnepa", "developer", "33", "2016-03-
22", 1575);
console.log(me.saySomething());
console.log(me.getMonthlySalary());

[ 21 ]
The output resulting from the preceding code is shown in the following figure:

As you can see in the preceding example, to invoke a class, we need to use the new
keyword. We do not do this directly as you would do with a function object in
ECMAScript 5 (Person()).

The let keyword


Similarly to var, the let keyword can be used to instantiate new variables. However,
when the let keyword is used inside a block within a function, the new variable is
only available inside such a block. Let's illustrate this with the following example:
guessName();
function guessName() {
var sayName = "John Doe";
if (sayName === "John Doe") {
let msg = `the name is ${sayName}`
What you need to know about JavaScript

console.log(`Inside the block ${msg}.`)


}
console.log(`Outside the block ${msg}.`)
}

The examples in this chapter can be found in


http://www.es6fiddle.net/inxmdigd/.

This is shown in the following figure. Note how the use of the variable that is declared
through let is defined as valid within the if block where it is instantiated, whereas
outside it is not declared:

Using let to declare variables inside a block

You can use the let keyword to create variables whose scope is
the current block, and var when the desired scope is a function.
Outside a code block, var and let can be used interchangeably.

[ 23 ]
What you need to know about JavaScript

Bringing It All Together with


Visual Studio Code
In previous sections, we discussed the fundamentals of JavaScript and reviewed
some of the new features that were brought by the latest version of the language,
ECMAScript 6. As you can see for yourself in the last section, this specification allows
us to write highly-scalable JavaScript code that is easier to read and to maintain.

To put this all together, let's now write a simpleyet fully functionalweb
application, where we will apply the concepts that were covered up to this point,
alongside the use of external JavaScript libraries and Cascading Style Sheets (CSS)
to make it look nice and behave as we want it to.

Choosing an integrated development


environment
To write our web application, we will need to choose an Integrated Development
Environment (also known as IDE for short) if we have not done so already. While
it is true that we can write HTML code, JavaScript libraries, and Cascading Style
Sheets using a simple text editor (such as Nano, Gedit, Pluma, or Vim in Linux,
and Notepad or Notepad++ in Windows), it is preferable to use an IDE as it allows
you to manage your project by folders, provides debugging tools, and, in most cases
(if not all), has built-in intelligent code completion.

In this section, we will introduce you to Visual Studio Code, a lightweight IDE
optimized-for-building web applications, which was developed and released by
Microsoft not too long ago. Visual Studio Code not only presents the advantage
of being available for Windows, Linux, and Mac OS, but also it is free.

[ 24 ]
What you need to know about JavaScript

To download it, go to https://code.visualstudio.com/, choose


your operating system, and install it on your machine before proceeding
further. We chose Visual Studio Code as the IDE for this project because
it is available for all the major operating systems, it is lightweight, and
you can download and install it free in as many machines as you like.
If you prefer to use a regular text editor, such as the ones mentioned
earlier, or another IDE of your choice (such as Netbeans or even the
full-featured Visual Studio suite), feel free to do so.

Creating directories and files for our web


application with Visual Studio Code
Regardless of whether you are planning on creating a web application that consists
of a complex directory structure (with many folders and subfolders) or a simple
one, it is a good idea to start off as organized as possible. In our case, we are going
to create a simple directory structure with only one file (index.html) at the top and
two subdirectories: styles (for Cascading Style Sheets), and scripts (for homemade
JavaScript files with custom functions).

To illustrate the concepts that were covered in previous sections, we will create a
web application that will allow us to enter a list of to-do tasks for the current day
using a simple form (input textarea and a button). Once we have completed a task,
we can mark it as complete. If we want to remove a task, we will be able to do so,
and mark it back as not completed if we wish. Although no persistence will be
provided in the scope of our demonstration (tasks will be lost when we close the
web page), we will provide a few suggestions that you may want to consider in
order to save records permanently.

To begin, follow these steps:

1. Create a folder in a location of your choice and give it a descriptive name,


such as webapp. Then, launch Visual Studio Code and go to File | Open
folder to select the root directory of your project.
2. Click on the project name and create two new directories in the root folder
with the names that we mentioned earlier. Finally, create a file named
index.html in the same location. When you are done, your directory
structure should look similar to the following figure:

[ 25 ]
What you need to know about JavaScript

Viewing the directory structure of our project

We will go over the index.html, styles/styles.css, and


scripts/script.js files in detail.

3. Select the index.html file and paste the following HTML structure into
it, which represents the basic skeleton of a HTML5 file. We will add more
content in the subsequent steps:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
</head>
<body>
<header>
</header>
</body>
</html>

4. Inside the <head> and </head> tags, reference the external Cascading Style
Sheets and, optionally, a Google font of your choice to enhance the visual
experience. In this case, we will use a font named Indie Flower (quick view
available at https://www.google.com/fonts/specimen/Indie+Flower):
<link rel='stylesheet'
href='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/
bootstrap.min.css' type='text/css'>
<link href=
'https://fonts.googleapis.com/css?family=Indie+Flower'
rel='stylesheet' type='text/css'>
<link rel="stylesheet" href=
"https://maxcdn.bootstrapcdn.com/font-awesome/
4.6.1/css/font-awesome.min.css">
<link rel='stylesheet' href='styles/style.css'
type='text/css'>

[ 26 ]
What you need to know about JavaScript

As you can see in the preceding code, we will include Bootstrap (the popular
HTML/CSS/JavaScript framework) and FontAwesome (the iconic font
designed for Bootstrap) in our project. These tools will help us make our
application responsive and good-looking at the same time. Additionally,
we will include our own styling sheet (style.css inside the styles folder)
to add some finishing touches to the user interface.

Bootstrap (http://getbootstrap.com/) and FontAwesome


(https://fortawesome.github.io/Font-Awesome/), along
with jQuery (http://jquery.com/), are available for download
from their respective websites but, even when you can include the
actual files inside your project, it is a good idea to use a Content
Delivery Network (CDN) to save on bandwidth and make it
easier to manage your web application.

5. Inside the <header> and </header> tags, insert the code for the header
(top section) of the page. Don't worry about the empty h1 tags. We will
add content through JavaScript later:

Bootstrap exposes a 12-column grid system and several classes to help


us distribute content in a web page depending on the screen sizes. In
the following code, col-xs-12 col-md-6 indicates that the content
inside h1 tags should occupy the total available view area for extra-small
devices (cell phones) and small ones (for example, tablets) but only half
the size of the screen for medium-sized devices up to big monitors. By
default, a styling applied to a given screen size applies to larger devices
as well unless overridden by an explicit configuration for a larger size.
In this example, col-md-6 overrides col-xs-12 for medium-sized
devices and larger sizes. To know more about Bootstrap's grid system,
you can refer to the official documentation at http://getbootstrap.
com/css/.

<header>
<div class="container">
<div class="row">
<div class="col-xs-12">
<h1><i class="fa fa-calendar"></i></h1>
</div>
</div>
</div>
</header>

[ 27 ]
What you need to know about JavaScript

6. Below the header tags, insert the code for the form and the ul tags where we
will later place the task list using JavaScript. As in the previous step, we will
use icons that are provided by FontAwesome inside the <i> and </i> tags:
<div class="main">
<div class="container">
<div class="row">
<form class="form">
<div class="col-xs-12 col-md-4">
<input id="comment" type="text" placeholder="Write
description">
</div>
<div class="col-xs-12 col-md-4">
<button type="submit" class="button"><i class="fa
fa-plus"></i>Add task</button>
</div>
</form>
</div>

<ul class="tasks" id="tasks">


</ul>
</div>
</div>

7. In order to add interactivity to our page, we need to include jQuery and our
own JavaScript file with custom functions. By adding the following two lines
right above the closing </body> tag, we ensure that both files are invoked
once the entire page has been loaded. This will make the page load faster
and does not affect the functionality at all:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.3/
jquery.min.js"></script>
<script src="scripts/script.js"></script>

At this point, your index.html file should look like the following:
<!DOCTYPE html>
<html lang="en">
<head>
<link href=
'https://fonts.googleapis.com/css?family=Indie+Flower'
rel='stylesheet' type='text/css'>
<link rel="stylesheet" href=
"https://maxcdn.bootstrapcdn.com/font-
awesome/4.6.1/css/font-awesome.min.css">
<link rel='stylesheet' href=
'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/
bootstrap.min.css' type='text/css'>

[ 28 ]
What you need to know about JavaScript

<link rel='stylesheet' href='styles/style.css'


type='text/css'>
<meta charset="utf-8" />
</head>
<body>
<header>
<div class="container">
<div class="row">
<div class="col-xs-12">
<h1><i class="fa fa-calendar"></i></h1>
</div>
</div>
</div>
</header>

<div class="main">
<div class="container">
<div class="row">
<form class="form">
<div class="col-xs-12 col-md-4">
<input id="comment" type="text"
placeholder="Write description">
</div>
<div class="col-xs-12 col-md-4">
<button type="submit" class="button"><i
class= "fa fa-plus"></i>Add task</button>
</div>
</form>
</div>

<ul class="tasks" id="tasks">


</ul>
</div>
</div>
<script src=
"https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.3/
jquery.min.js"></script>
<script src="scripts/script.js"></script>
</body>
</html>

However, if you open this in your web browser, it will not look nearly as we
wish. Thus, we will add some custom styling to beautify it a bit.

[ 29 ]
What you need to know about JavaScript

8. In styles/styles.css, we will add the styles that we want to apply to


the sections of and classes declared in index.html (font types and sizes,
margins, colors, and so on). For example, the following block indicates
the styles that should be applied to content inside h1 tags. Feel free to
experiment with colors (which is something that I usually like to do using
the CSS 3.0 Maker at http://www.css3maker.com/css-3-rgba.html):
h1 {
font-size: 36px;
font-weight: 400;
color: rgba(39, 135, 255, 0.9);
}

That said, your styles/styles.css file should look like the following:

Again, feel free to experiment with these settings and add others if
you want. To learn more about CSS, go to https://www.w3.org/
Style/CSS/learning, where you will find plenty of resources to
brush up your styling skills.

html, body {
font-family: 'Indie Flower', sans-serif;
}

h1 {
font-size: 36px;
font-weight: 400;
color: rgba(39, 135, 255, 0.9);
}

.main {
margin-top: 50px;
}

form.input {
background: #f0f0f0;
border: none;
border-left: 2px solid #fff;
font-size: 36px;
padding-left: 20px;
width: 100%;
transition: background 2s, border-left 2s;
}

[ 30 ]
What you need to know about JavaScript

form.input:focus {
background: #fff;
border-left: 2px solid #000;
box-shadow: none;
outline: none;
}

button.btn {
background: transparent;
border: 2px solid #000;
color: #00f28f;
cursor: pointer;
font-size: 36px;
padding: 20px 24px;
transition: background 2s, color 2s;

button.btn.hover{
background: #00f28f;
color: #fff;
}

tasks {
margin-top: 20px;
list-style: none;
padding-left: 0px;
}

li {
padding-left: 20px;
border-left: 3px solid #000;
font-size: 36px;
margin: 25px 0 0px;
}

fa.fa-check {
color: rgba(76, 141, 44, 0.9);
}

fa.fa-times {
color: rgba(215, 40, 40, 0.9);
padding-right: 10px;
padding-left: 10px;

[ 31 ]
What you need to know about JavaScript

fa.fa-calendar {
padding-right: 15px;
}

li.done {
background: #CCFF99;
}

Each time you specify a color using either an RGB or RGBA notation, Visual
Studio Code will show you the chosen color in a small square, as shown in the
following figure:

Displaying the color in Visual Studio Code

At this point, your web page must look a little nicer but, unfortunately, it will not
do anything until we add code to scripts/script.js. As this file is the place
where we will add the working logic of our application, it deserves a careful and
thorough explanation.

Writing JavaScript code for our


application
Once we have written the HTML and the styles for the page, it's time to write the
code that will add the desired functionality.

As you start working on the JavaScript side of things, you may want
to review, at least briefly, the documentation that is available for
the jQuery API at http://api.jquery.com/. This will help you
remember how the functions we will use in the following steps work.

[ 32 ]
What you need to know about JavaScript

1. We begin by creating a class named Task with the following constructors:


id, description, entryDate, and isCompleted. These fields will help us
identify and describe each task, which will have a corresponding entry date
and a flag to indicate whether it has been completed or not:
class Task {
constructor(id, description, entryDate, isCompleted) {
this.id = id;
this.description = description;
this.entryDate = entryDate;
this.isCompleted = isCompleted;
}
}

2. The initial function that is executed when the file is invoked is usually named
main, as we can see in the following code. To reference this more easily later
(at the bottom of the file, as we will see), we will store it inside a variable
with the same name using an arrow function:
var main = () => {
};

Inside the function block, we will now add the code that will store today's
date into a variable conveniently named today, create an empty array to
store the task objects, add content (page title and current date) inside the h1
tags, capture the content of the input textarea, save it into a variable named
input and add it inside the ul area if the task description is not empty, count
the number of tasks that are already added to the list to assign the proper
value to the id field of the task object, add the task object to the array, and
clear the input textarea to enter another task if needed, and prevent the form
from performing its default action (getting submitted).
All of the preceding actions will be performed by the following code. Note
how the page title and the task list lines make use of template strings, and
that the form submission event is handled through another arrow function:
// Add date in page title
var today = new Date().toDateString();
// Create an array to store tasks
var myTasks = [];
$('h1').append(`My tasks for today, ${today}`);
// Add tasks to the list
$('form').submit((event) => {
var input = $(event.target).find('input');
var description = input.val();
if (description != ""){

[ 33 ]
What you need to know about JavaScript

var currentTaskCount = $("#tasks").children().length;


task = new Task(currentTaskCount + 1, description,
today, false);
myTasks.push(task);
var html = $('<li>').html(`<i class="fa
fa-check"></i><i class="fa
fa-times"></i>${task.description}`);
html.appendTo('#tasks');
input.val("");
}
return false;
});

Note that, when you add a task in the input textarea and click on the +Add
task button, a task is added below along with a green checkmark and a red X
at the beginning, as shown in the following figure:

Populating our task list

3. Also, inside main, let's add the code that will allow us to remove a certain
task by clicking on the associated red X. In simple terms, the following five
lines of code will remove the li element where the red X you just clicked
on resides and also delete the corresponding item from the tasks array:
$('#tasks').on('click', '.fa.fa-times', function(event) {
var selectedTask = $(this).closest("li").index();
myTasks.splice(selectedTask, 1);
$(this).closest("li").remove();
});

[ 34 ]
What you need to know about JavaScript

Why did we use a regular function here instead of an arrow one? The answer
is simple. It is because arrow functions do not have their own this value, but
they inherit it from the closing scope. Had we used an arrow function here,
this inside the block would point to the actual index.html file that we are
working on.

4. Finally, we will add the code that will mark tasks as complete by updating
the isComplete flag to true and adding a green highlight to the li element.
In addition to this, we will be able to remove the complete flag and reset the
background highlight (turn the li.done class on and off) by clicking on the
green check mark again:
$('#tasks').on('click', '.fa.fa-check', function(event) {
var selectedTask = $(this).closest("li").index();
$(this).closest("li").toggleClass('done');
if ($(this).closest("li").hasClass('done')) {
myTasks[selectedTask].isCompleted = true;
}
else{
myTasks[selectedTask].isCompleted = false;
}
});

Once you have completed the preceding steps, add the following line at the bottom
of the file (outside the main function definition). This will ensure that the content of
the file is invoked when the index.html finishes loading:
$(document).ready(main);

That said, your scripts/script.js file should look like the following:
class Task {
constructor(id, description, entryDate, isCompleted) {
this.id = id;
this.description = description;
this.entryDate = entryDate;
this.isCompleted = isCompleted;
}
}

var main = () => {


// Add date in page title
var today = new Date().toDateString();
// Create an array to store tasks
var myTasks = [];

[ 35 ]
What you need to know about JavaScript

$('h1').append(`My tasks for today, ${today}`);


// Add tasks to the list
$('form').submit((event) => {
var input = $(event.target).find('input');
var description = input.val();
if (description != "") {
var currentTaskCount = $("#tasks").children().length;
task = new Task(currentTaskCount + 1, description, today,
false);
myTasks.push(task);
var html = $('<li>').html(`<i class="fa fa-check"></i><i
class="fa fa-times"></i>${task.description}`);
html.appendTo('#tasks');
input.val("");
}
return false;
});
// Remove tasks by clicking on the red X
$('#tasks').on('click', '.fa.fa-times', function(event) {
console.log($(this).closest("li").index());
var selectedTask = $(this).closest("li").index();
myTasks.splice(selectedTask, 1);
$(this).closest("li").remove();
console.log(myTasks);
});
// Highlight task (and mark it as complete) by clicking on the
green check mark
$('#tasks').on('click', '.fa.fa-check', function(event) {
var selectedTask = $(this).closest("li").index();
$(this).closest("li").toggleClass('done');
if ($(this).closest("li").hasClass('done')) {
myTasks[selectedTask].isCompleted = true;
}
else {
myTasks[selectedTask].isCompleted = false;
}
console.log(myTasks);
});
};
$(document).ready(main);

We are now ready to test drive our applicationnot just add tasks as we did
previously but also remove them and change their status as well.

[ 36 ]
What you need to know about JavaScript

Testing our application


Now, we get into the most-awaited phase: testing your application.

To view a file in its associated default application, press F1 and enter ext install
view in default application in the search box, as shown in the following figure,
and click on the only search hit. This will allow you to open index.html in your
default browser from Visual Studio Code directly when you press F1 again and click
on the newly-installed View in Default Application extension. Additionally, you
may want to have a look at the list of extensions that are available to enhance your
experience with the IDE:

Installing the View in Default Application extension for Visual Studio Code

To open the file using your default browser, you will need to place the focus on this
file by selecting it from the file explorer section on the left. Keep in mind, however,
that we will need to refresh the page in order to apply the changes that we just made
to the JavaScript file.

[ 37 ]
What you need to know about JavaScript

Let's now add the same tasks as we did earlier. Three console.log(myTasks)
statements placed conveniently (as can be seen in the following figure) will help us
visualize the contents of the task array (myTasks) each time we add an item to the
list and after we remove one or mark the task as complete:

Displaying the contents of the array using the web developer console

[ 38 ]
What you need to know about JavaScript

After adding the items to the list, our array should look as indicated in the following
figure. If we mark Shop for groceries as complete by clicking on the green check
mark and remove Take kids to school from the list by clicking on the associated red
X, the array will be modified accordingly as can be seen in the following figure:

Displaying the array contents before and after making changes to the list

You can run this example at https://jsfiddle.net/


gacanepa/msy09y4m/.

As we can see, we created a basic web application to add daily activities to a list
where we can change their status when complete or remove them if our plans
change. Through the use of ECMAScript 6, we were able to group tasks into objects
of the same type so that they can be more accessible for later processing.

If you want to store your tasks persistently, you may want to


consider implementing a database in the backend or using either
Firebase (https://www.firebase.com/) or Cloudboost
(https://www.cloudboost.io/), two online platforms that
provide database storage for cloud applications.

[ 39 ]
What you need to know about JavaScript

To the Future and Beyond


Each year, ECMA International releases a new specification of JavaScript (or
more accurately, the ECMA-262 standard). Before the latest version came out
(this is ECMAScript 6, which we have discussed in earlier sections, also known as
ECMAScript 2015) in June 2015, preparations for the next one (ECMAScript 7 or
2016) had already begun. That said, we can reasonably expect a continuous flow
of new versions of the standard periodically as this has been the case in the past.

Note that ECMA International takes input from the community about
which features should be considered to be added in a new version of
the standard. These proposals are available at https://github.
com/tc39/ecma262. As new ideas are submitted, they undergo a
thorough revision by members of ECMA International, and status
updates are always published in the same repository as they progress
from Stage 0 (where input is allowed into the specification) until Stage
4, where the proposed addition has been formally accepted to go into
the next version of the standard.

What's in the near future of JavaScript?


According to the ECMAScript's GitHub page (refer to the link in the preceding
information box), the next version of the standard will most likely include the
following features, among others:

Array.includes: This iterates over the elements of the array in ascending


order (beginning at a given position, which is the beginning of the string if
omitted) to search for a specific element. If such an element is found at any
position, this returns true; otherwise, it returns false. In addition to this,
the includes function can be applied to any type of object (not only arrays),
though it is more likely to be used with arrays most of the time. This feature
is already part of the ECMAScript 7 specification.

[ 40 ]
What you need to know about JavaScript

The following code snippet will help us illustrate this:


var famousWriters = [];
famousWriters.push("C. S. Lewis");
famousWriters.push("J. K. Rowling");
famousWriters.push("J. R. R. Tolkien");
famousWriters.push("Richard Bach");

Given the preceding array, the following statements will evaluate to true:
famousWriters.includes("C. S. Lewis");
famousWriters.includes("Richard Bach");

Whereas the next statements will return false:


famousWriters.includes("C. S. Lewis", 1);
famousWriters.includes("John Doe");

Even when "C. S. Lewis" belongs to the array, famousWriters.


includes("C. S. Lewis", 1) begins the search at the second element of
the zero-based index array.
The next three features are not compatible with the current versions of
modern browsers as of May 2016:

Object.values/Object.entries: This feature is already in Stage 4 of ECMAScript


8 (2017). This feature allows you to retrieve value or key-value pairs from
objects for the purposes of iteration and serialization, as the documentation states.
Let's take the following example:
var person = { name: "Gabriel", age: 33, profession:
"developer" };

For this example, consider the following statement


console.log(Object.values(person));

This should return the following:


['Gabriel', 33, 'developer']

Likewise, also consider the following statement:


console.log(Object.entries(person));

This statement should return the following:


[ ['name', 'Gabriel'], ['age', 33], ['profession',
'developer'] ]

Even when these features are part of ECMAScript 8, they are expected to be
compatible with the next versions of major modern browsers.

[ 41 ]
What you need to know about JavaScript

String padding: This feature is also in Stage 3 as of May 2016. Until


ECMAScript 6, there were no native methods to pad a string, whereas
most modern popular languages implement similar functions. Today,
when the need for padding arises, developers have to resort to a wide
variety of inefficient methods and workarounds. Making string padding
an official part of the specification will provide a standardized solution
that will improve performance of applications.
The padStart() and padEnd() method pads the current string with a
specific string (eventually repeated) so that the resulting string reaches
a desired length. Depending on the case, the pad is applied from the
beginning (left) or from the end (right) of the current string, respectively.
If the pad string is not specified, a space is used by default.
For example, consider the following statement:
console.log(1.padStart(10));

This will print the following:


" 1"

Similarly, consider the following statement:


console.log('1'.padStart(10, "0"));

This will return the following:


"0000000001"

On the other hand, let's take a different example:


console.log('1'.padEnd(10));

This statement will output the following:


"1 "

Similarly, consider the following example statement:


console.log('1'.padEnd(10, "0"));

This will result in the following:


"1000000000"

When the specified padding is less than or equal to the length of the original
string, no padding characters are added. Let's take the following two
statements as an example. This is the first statement:
console.log('2016'.padStart(4, "0"));

[ 42 ]
What you need to know about JavaScript

The second statement is as follows:


console.log('2016'.padEnd(3, "0"));

Both these statements will return the following:


"2016"

These are only three of the new features that will soon become a part of the
ECMAScript standard. You can refer to the full list, along with a detailed browser
compatibility, at http://kangax.github.io/compat-table/esnext/.

The examples in this section are illustrated in https://jsfiddle.net/gacanepa/


sr6oyk0u/.

As we approach the date when the ECMAScript 7 specification goes from draft
to published, we can say without fear of being wrong that JavaScript will remain
the main and the most widely-used programming language for the web in the
foreseeable future. New features will continue to be added to make it a cleaner
language with which both beginners and experts get along just fine.

[ 43 ]
What you need to know about JavaScript

JavaScript Cheat Sheet


In this last section of the eGuide, we will share a brief JavaScript cheat sheet that we
hope you will find useful, both as a reminder and as a reference. You can refer to this
section of the eGuide when you need to find quick help and usage examples for each
JavaScript object type.

In the following lists, the output of a statement or expression is given as a comment


(following the two forward slashes).

Reviewing the number object


The number JavaScript base object allows us to work with numerical values. Rather
than performing actual mathematical operations, number lets us query an argument
to see whether it matches certain conditions (that is, is it an integer?) or modify its
format (for example, define the number of decimal digits in the output):

Number.isNaN(value): This returns true if the value is of the Number type


and evaluates to NaN; otherwise, this is false. This should not be confused
with the isNaN global, which attempts to convert the value and then tests it:
Number.isNaN(3); //false
Number.isNaN("hi there"); //false
Number.isNaN(Math.sqrt(-1)); //true
Number.isNaN(0/0); //true

Number.isInteger(): This returns true if the argument is an integer;


otherwise, this is false:
Number.isInteger(2); //true
Number.isInteger(3.5); //false
Number.isInteger("a"); //false
Number.isInteger(3500); //true

[ 44 ]
What you need to know about JavaScript

Number.prototype.toFixed(n): This returns the number given by Number.


prototype in fixed-point notation with n number of decimal places. This
rounds up when the digit in the (n + 1) position is greater than or equal to 5:
var a = 2.6742252;
a.toFixed(1); //"2.7"
a.toFixed(2); //"2.67"
a.toFixed(3); //"2.674"
a.toFixed(5); //"2.67423"

Working with strings


The string object allows you to manipulate text strings or sequences of characters
that are composed of one or more characters. The string variables are often used
to store data in text form:

String.prototype.length: This returns the length of the string that is


specified by String.prototype
String.prototype.charAt(value): This returns the character at the
index given by value
String.prototype.charCodeAt(value): This returns the Unicode
equivalent of the character found at the index given by value
String.prototype.includes(value): This returns true if the value is
found inside another String.prototype; otherwise, this is false
String.prototype.indexOf(value): This returns the index where the
first occurrence of the value is found (if it exists); otherwise, this is -1
String.prototype.lastIndexOf(): This returns the index where the
last occurrence of the value is found (if it exists); otherwise, this is -1
String.prototype.startsWith(value): This returns true if a string
starts with the value
String.prototype.substring(value1, value2): This returns the
substring found between two indexes (value1 and value2 where
value2 > value1)
String.prototype.toLowerCase(): This converts the string to lowercase
String.prototype.toUpperCase(): This converts the string to uppercase

[ 45 ]
What you need to know about JavaScript

Here is an example for your reference:


var sentence = "We all live in a yellow submarine";
sentence.length; //33
sentence.charAt(17); //"y"
sentence.charCodeAt(17); //121
sentence.includes("sub"); //true
sentence.includes("Beatles"); //false
sentence.indexOf("a"); //3
sentence.lastIndexOf("a"); //28
sentence.startsWith("We"); //true
sentence.startsWith("all live in"); //false
sentence.endsWith("marine"); //true
sentence.endsWith("submarine"); //true
sentence.endsWith("Great song!"); //false
sentence.substring(7, 23); //"live in a yellow"
sentence.toLowerCase(); //"we all live in a yellow submarine"
sentence.toUpperCase(); //"WE ALL LIVE IN A YELLOW SUBMARINE"

Boolean object fundamentals


Boolean variables can store either one of two values: true or false. If you are
interested in converting the value of a variable to a string in order to use it in
an expression, or if you want to assign the same value to another variable,
the following methods will help you get the job done:

Boolean.prototype.toString(): This returns true or false (as strings),


based on the Boolean value of the variable (true or false, respectively):
var x = true;
x; //true
x.toString(); //"true"

Boolean.prototype.valueOf(): This returns the Boolean value of


the variable. Typically, this is used to assign the value of the given
Boolean.prototype to another variable:
var y = x.valueOf();
y; //true

[ 46 ]
What you need to know about JavaScript

Grouping statements into functions


Also known as methods in other programming languages, JavaScript functions allow
you to group statements in a single block that can be invoked at will in several places
of the code. Thus, if a change needs to be made to correct an error or implement a
feature, the code of the function has to be modified in one place only:
// Declare function
function name(arg1, arg2, , argN) {
// Javascript expressions here
}
// Call function
var result = name(value_for_arg1, value_for_arg2, ,
value_for_argN);
Result;

An example of this is as follows:


function isAdult(age) {
if (Number.isInteger(age)) {
if (age >= 18) {
return "You are an adult";
}
else {
return "You are a minor";
}
}
else {
return "You have entered an invalid age";
}
};
var result = isAdult(15); //"You are a minor"
var result = isAdult(99); //"You are an adult"
var result = isAdult("AA"); //"You have entered an invalid age"

Using arrow functions, the result is the same, which is as follows:


var result = (age) => {
if (Number.isInteger(age)) {
if (age >= 18) {
return "You are an adult";
}
else {
return "You are a minor";
}

[ 47 ]
What you need to know about JavaScript

}
else {
return "You have entered an invalid age";
}
};
result(18); //"You are an adult"
result(16); //"You are a minor"
result("CC"); //"You have entered an invalid age"

Getting started with arrays


In simple terms, an array is a list-like object. Let's have a look at the most
frequently-used methods:

Array.prototype.push: This adds element(s) to the end of the array


given by Array.prototype.
Array.prototype.unshift: This adds new item(s) to the beginning of
an array.
Array.prototype.length: This gets the length (number of items) of the
array.
Array.prototype[n]: This accesses the item in position n of the array. This
returns undefined if it the given position does not exist within the array.
Array.prototype.forEach(callback, [, thisArg]): This executes a
function on each element in the array. The callback is a function that takes
three mandatory arguments (this is the current element in the iteration, its
index, and array, which is a placeholder for the array being examined).
Additionally, thisArg is an optional argument that can be used to define
the this value when the callback function is executed.
Array.prototype.pop(): This removes the last item of an array.
Array.prototype.shift(): This removes the first item of an array.
Array.prototype.splice(pos, n): This removes n number of elements
starting at the position specified by pos.
Array.prototype.slice(): This copies an array into another variable.

An example of this is as follows:


var fairyTales = [];
fairyTales.push("Cinderella");
fairyTales.unshift("Beauty and the Beast");
fairyTales.unshift("The little mermaid");

[ 48 ]
What you need to know about JavaScript

fairyTales; //Array [ "The little mermaid", "Beauty and the Beast",


"Cinderella" ]
fairyTales[1]; //"Beauty and the Beast"
fairyTales.length; //3
fairyTales.forEach(function (item, index, array) {
console.log(item, index);
});
//The little mermaid 0
//Beauty and the Beast 1
//Cinderella 2
var fairyTalesOrig = fairyTales.slice();
fairyTalesOrig; //Array [ "The little mermaid", "Beauty and the
Beast", "Cinderella" ]
fairyTales.pop();
fairyTales; //Array [ "The little mermaid", "Beauty and the Beast" ]
fairyTales.shift(); //"The little mermaid"
fairyTales; //Array [ "Beauty and the Beast" ]

Fundamentals of date objects


Date objects are used to represent a fixed date and time:

Date.prototype.getDate(): This returns the day of the month (1-31) for


the date specified by Date.prototype, which must follow the guidelines
outlined in IETF-compliant RFC 2822 for timestamps.
Date.prototype.getDay(): This returns the day of the week (0-6).
Date.prototype.getFullYear(): This returns the year.
Date.prototype.getHours(): This returns the hour (0-23).
Date.prototype.getMinutes(): This returns the minutes (0-59).
Date.prototype.getMonth(): This returns the month (0-11).
Date.prototype.getSeconds(): This returns the seconds (0-59).
Date.prototype.getTime(): This returns the number of milliseconds
since January 1, 1970, 00:00:00 UTC. For prior dates, the result is a
negative number.
Date.prototype.toString(): This returns the string representation of
Date.prototype.

[ 49 ]
What you need to know about JavaScript

Here is an example:
var myBirthDate = new Date(Date.UTC(1983,0,15,13,09,05));
myBirthDate; //Date 1983-01-15T13:09:05.000Z
myBirthDate.getDate(); //15
myBirthDate.getDay(); //6
myBirthDate.getFullYear(); //1983
myBirthDate.getHours(); //10
myBirthDate.getMinutes(); //9
myBirthDate.getMonth(); //0
myBirthDate.getSeconds(); //5
myBirthDate.getTime(); //411484145000
myBirthDate.toString(); //"Sat Jan 15 1983 10:09:05 GMT-0300 (ART)"

Introducing assignment and arithmetic


operators
In order to perform assignments of values to variables or an arithmetic operation,
JavaScript uses the following guidelines:

=: This assigns a value to a variable


+=: This adds a value to the current value of a variable
-=: This subtracts a value from the current value of a variable
*=: This multiples the current value of a variable
/=: This divides the current value of a variable
%=: This returns the remainder of a division to a variable
+ and +=: These operators are also used to concatenate strings
+, -, *, and /: These operators are used for the usual arithmetic operations
when used with numbers
++ and --: These operators are used to increment or decrement the value of a
variable, respectively

An example of this is the following:


var x = 10;
x; //10
x += 2; //12
x -= 7; //5
x *= 9; //45
x /= 9; //5

[ 50 ]
What you need to know about JavaScript

x %= 3; //2
x = x++;
3
x = --x;
2

Using comparison operators


When we need to determine a course of action based on the comparison between two
variables, JavaScript provides the following operators:

a < b: This is true if b is greater than a; otherwise, this is false.


a <= b: This is true if b is greater than or equal to a; otherwise, this is false.
a > b: This is true if a is greater than b; otherwise, this is false.
a >= b: This is true if a is greater than or equal to b; otherwise, this is false.
a == b: This is true if a is equal to b; otherwise, this is false.
a === b: This is true if a is equal to b and both variables are of the same
type; otherwise, this is false.
a != b: This is true if a and b are not equal; otherwise, this is false.
a !== b: This is true if a and b are not equal or if they are of different types;
otherwise, this is false.

An examples of this is as follows:


var a = 15;
var b = 18;
a > b; //false
a !== b; //true
var x = 15;
var y = 15;
x == y; //true
x === y; //true
var z = "15";
x == z; //true
x === z; //false

[ 51 ]
What you need to know about JavaScript

Several possible courses of action Using


the switch-case control structure
When there are several "forks in the road" (that is, courses of action depending
on the values of variables), a switch-case control structure can be our best friend.
This will allow us to perform different actions that are based on the value of the
control variable:

Refer to Section 1 for other control structures and loops.

switch (variable) {
case value1:
//Actions to perform if variable=value1
break;
case value2:
//Actions to perform if variable=value2
break;
default:
//Actions to perform if variable is not equal to value1 or
value2
break;
}

Let's consider the following example:


var currentTime = new Date();
currentTime.getHours(); //20
var currentHour = currentTime.getHours();
switch (true) {
case (currentHour < 12):
console.log("Good morning!");
break;
case (currentHour > 12 && currentHour < 17):
console.log("Good afternoon!");
break;
default:
console.log("Good evening!");
break;
};

[ 52 ]
What you need to know about JavaScript

Given the current hour of day, as indicated by currentHour, the switch-case control
structure should return the following:
Good evening!

The examples in this chapter can be found at


http://jsfiddle.net/gacanepa/qu3rzjmq/.

Summary
In the first section, we reviewed some fundamental programming concepts
of JavaScript.

Moving to the second section, we introduced the most distinguishing features of


ECMAScript 6: template strings, tagged templates, arrow functions, classes and
inheritance, and the let keyword. Particularly, we showed you how these tools
can help us write cleaner and more maintainable code when compared to previous
specifications of the language.

In the next section, we put everything together in a basic, yet fully-functional, web
application. We created a basic web application to add daily activities to a list where
we could change their status when complete or remove them if our plans change.
Through the use of ECMAScript 6, we were able to group tasks into objects of the
same type so that they could be more easily accessed for later processing.

In this last section of the eGuide, we shared a brief JavaScript cheat sheet that
you can refer to when you need to find quick help and usage examples for each
JavaScript object type.

[ 53 ]
What you need to know about JavaScript

What to do next?

Broaden your horizons with Packt


If you're interested in JavaScript, then you've come to the right place. We've got
a diverse range of products that should appeal to budding as well as proficient
specialists in the field of JavaScript.

[ 54 ]
What you need to know about JavaScript

To learn more about JavaScript and find out what you want to learn next, visit the
JavaScript technology page at https://www.packtpub.com/tech/javascript.

If you have any feedback on this eBook, or are struggling with something we haven't
covered, let us know at customercare@packtpub.com.

Get a 50% discount on your next eBook or video from www.packtpub.com using
the code:

[ 55 ]

You might also like