Professional Documents
Culture Documents
about JavaScript
Gabriel Cnepa
BIRMINGHAM - MUMBAI
What you need to know about JavaScript
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.
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
https://www.packtpub.com/books/subscription/packtlib
Why subscribe?
Fully searchable across every book published by Packt
Copy and paste, print and bookmark content
On demand and accessible via web browser
[i]
Table of Contents
[ ii ]
Preface
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.
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.
[ 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.
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';
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;
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:
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:
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
The bottom line is: you pick your poison! Just don't forget to be consistent.
[4]
What you need to know about JavaScript
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];
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')}};
Likewise, you can store HTML elements in object variables, as we will show you in
the example near the end of this chapter.
[6]
What you need to know about JavaScript
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:
[7]
What you need to know about JavaScript
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:
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.
The SayHi project requires 3 parameters: your name, age, and profession
(in that order).
[9]
What you need to know about JavaScript
/* 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.
[ 11 ]
What you need to know about JavaScript
[ 12 ]
What you need to know about JavaScript
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:
[ 13 ]
What you need to know about JavaScript
The preceding example is shown with more clarity in the following figure:
[ 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.
If you replace the return lines with two console.log() calls (one for each array),
the output should be shown in the following figure:
[ 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.
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:
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
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:
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.
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:
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()).
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:
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
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.
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 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.
[ 25 ]
What you need to know about JavaScript
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.
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:
<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>
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
<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>
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
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:
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.
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
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
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:
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;
}
}
[ 35 ]
What you need to know about JavaScript
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
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
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.
[ 39 ]
What you need to know about JavaScript
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.
[ 40 ]
What you need to know about JavaScript
Given the preceding array, the following statements will evaluate to true:
famousWriters.includes("C. S. Lewis");
famousWriters.includes("Richard Bach");
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
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
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/.
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
[ 44 ]
What you need to know about JavaScript
[ 45 ]
What you need to know about JavaScript
[ 46 ]
What you need to know about JavaScript
[ 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"
[ 48 ]
What you need to know about JavaScript
[ 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)"
[ 50 ]
What you need to know about JavaScript
x %= 3; //2
x = x++;
3
x = --x;
2
[ 51 ]
What you need to know about JavaScript
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;
}
[ 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!
Summary
In the first section, we reviewed some fundamental programming concepts
of JavaScript.
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?
[ 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 ]