Thejsway
Thejsway
Baptiste Pesquet
This book is for sale at http://leanpub.com/thejsway
This is a Leanpub book. Leanpub empowers authors and publishers with the Lean Publishing
process. Lean Publishing is the act of publishing an in-progress ebook using lightweight tools
and many iterations to get reader feedback, pivot until you have the right book and build
traction once you do.
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . i
About this book . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ii
Who this book is for . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ii
Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ii
User interactions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
Variable naming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
Coding time! . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
3. Add conditions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
TL;DR . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
What’s a condition? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
Alternative conditions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
Add additional logic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
Multiple choices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
Coding time! . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
4. Repeat statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
TL;DR . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
The while loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
The for loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
Common mistakes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
Which loop should I use? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
Coding time! . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
5. Write functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
TL;DR . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
Introduction: the role of functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
Discovering functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
Function contents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
Anonymous functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
Guidelines for programming with functions . . . . . . . . . . . . . . . . . . . . . . . 44
Coding time! . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
TL;DR . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
String recap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
Obtaining string length . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
Converting string case . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
Comparing two strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
Strings as sets of characters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
Searching inside a string . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
Breaking a string into parts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
More on Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
Coding time! . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163
Acknowledgments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164
Introduction
About this book
First thing first: thanks for having chosen this book. I hope reading it will be both beneficial and
pleasurable to you.
Overview
This book is divided into three main parts. The first one teaches the basics of programming with
JavaScript. The second one explains how to use JavaScript to create interactive web pages. The
third one deals with more advanced concepts of the language. Each part depends on the previous
ones, but there’s no other prerequisite to reading.
Each chapter starts with a TL;DR paragraph which summarizes it, so you’ll be able to skip ahead
if you already know a chapter’s content.
At the end of each chapter, a series of short and focused exercises will make you put your
newly acquired skills into practice. Searching them seriously is essential: real learning comes
with practicing, not just reading.
Complete beginner or already experienced in programming, I wish you a great journey in the
wonderful world of JavaScript!
Welcome to programming
TL;DR
• A computer is a machine whose role is to execute quickly and flawlessly a series of actions
given to it.
• A program is a list of actions given to a computer. These actions take the form of textual
commands. All these commands form the program’s source code.
• The programmer’s task is to create programs. To accomplish this goal, he can use different
programming languages.
• Before writing code, one must think ahead and decompose the problem to be addressed in
a series of elementary operations forming an algorithm.
What’s a program?
Evolution (?)
Since their invention in the 1950s, computers have revolutionized our daily lives. Calculating
a route from a website or a GPS, booking a train or plane ticket, or seeing and chatting with
friends on the other side of the world: all these actions are possible thanks to computers.
Let’s take the term “computer” in its broadest sense, meaning a machine that can
perform arithmetic and logical operations. It could mean either a desktop or laptop
computer (PC, Mac), a computing server, or a mobile device like a tablet or smartphone.
Nonetheless, a computer can only perform a series of simple operations when instructed to do
so. They normally have no ability to learn, judge, or improvise. They simple do what they’re
told to do! Their value comes from how they can quickly handle and process huge amounts of
information.
Welcome to programming iv
A computer often requires human intervention. That’s where programmers and developers come
in! They write programs that result in instructions to a computer.
A computer program (also called an application or software) is usually comprised of one or
more text files containing commands in the form of code. This is why developers are also called
coders.
A programming language is a way to give orders to a computer. It’s a bit like a human
language! Each programming language has vocabulary (keywords that each play a specific role)
and grammar (rules defining how to write programs in that language).
str:
.ascii "Hello\n"
.global _start
_start:
movl $4, %eax
movl $1, %ebx
movl $str, %ecx
movl $8, %edx
int $0x80
movl $1, %eax
movl $0, %ebx
int $0x80
Pretty scary, isn’t it? Fortunately, other programming languages are much more simpler and
convenient to use than assembly language.
Programming languages
There are a large number of programming languages, each adapted to different uses and with its
own syntax. However, there are similarities between the most popular programming languages.
For example, here’s a simple program written in Python:
Welcome to programming v
print("Hello")
<?php
echo("Hello\n");
?>
Or even C#!
class Program {
static void Main(string[] args) {
Console.WriteLine("Hello");
}
}
Program execution
The fact of asking a computer to process the orders contained in a program is called execution.
Regardless of which programming language is used, a program must be translated into assembly
code in order to be executed. The translation process depends on the language used.
With some languages, the translation into assembly code happens line by line in real time. In
this case, the program is executed like a human reads a book, starting at the top and working
down line-by-line. These languages are said to be interpreted. Python and PHP are examples of
interpreted languages.
Another possibility is to read and check for errors the whole source code before execution. If
no errors are detected, an executable targeting one specific hardware platform is generated. The
intermediate step is called compilation, and the programming language which use it are said to
be compiled.
Lastly, some languages are pseudo-compiled in order to be executed on different hardware
platforms. This is the case for the Java language and also for those of the Microsoft .NET family
(VB.NET, C#, etc).
Welcome to programming vi
Learn to code
Introduction to algorithms
Except in very simple cases, you don’t create programs by writing source code directly. You’ll
first need to think about the instructions you’ll want to convey.
Take a concrete example from everyday life: I want to make a burrito. What are the steps that
will enable me to achieve my goal?
Begin
Get out the rice cooker
Fill it with rice
Fill it with water
Cook the rice
Chop the vegetables
Stir-fry the vegetables
Taste-test the vegetables
If the veggies are good
Remove them from the stove
If the veggies aren't good
Add more pepper and spices
If the veggies aren't cooked enough
Keep stir-frying the veggies
Heat the tortilla
Add rice to tortilla
Add vegetables to tortilla
Roll tortilla
End
Welcome to programming vii
Mmmmmm!
You reach your goal by combining a set of actions in a specific order. There are different types
of actions:
We used a simple writing style, not a specific programming language. In fact, we just wrote
what is called an algorithm. We can define an algorithm as an ordered sequence of operations
for solving a given problem. An algorithm breaks down a complex problem into a series of simple
operations.
History of JavaScript
JavaScript is first and foremost the programming language of the web. It was invented in 1995
by Brendan Eich¹, who at the time worked for Netscape², which created the first popular web
browser (Firefox’s ancestor).
JavaScript should not be confused with Java, another language invented at the same
time! Both share a similar syntax, but their use cases and “philosophies” are very
different.
The idea behind JavaScript was to create a simple language to make web pages dynamic and
interactive, since back then, pages were very simple.
¹https://en.wikipedia.org/wiki/Brendan_Eich
²https://en.wikipedia.org/wiki/Netscape_Communications
Introducing JavaScript ix
Web builders starting gradually enriching their pages by adding JavaScript code. For this code
to work, the recipient web browser (the software used to surf the web) had to be able to process
JavaScript. This language has been progressively integrated into browsers, and now all browsers
are able to handle it!
Because of the explosion of the Web and the advent of the web 2.0 (based on rich, interactive
pages), JavaScript has become increasingly popular. Web browser designers have optimized the
execution speed of JavaScript, which means it’s now a very fast language.
This led to the 2009 emergence of the Node.js³ platform, which allows you to create JavaScript
web applications very quickly. Thanks to a service called MongoDB⁴, JavaScript has even entered
the database world (software whose role is to store information).
Finally, the popularity of smartphones and tablets with different systems (iOS, Android, Win-
dows Phone) has led to the emergence of so-called cross-platform development tools. They allow
you to write a single mobile application that’s compatible with these systems. These tools are
almost always based on… JavaScript!
³https://nodejs.org
⁴https://www.mongodb.com
Introducing JavaScript x
This book uses the most recently standardized version of JavaScript, called ES2015 or sometimes
ES6. This version brings a lot of interesting novelties to the table. It is now well supported by
most environments and platforms, starting with web browsers (more details in this compatibility
table⁷).
⁵https://medium.freecodecamp.com/what-programming-language-should-i-learn-first-%CA%87d%C4%B1%C9%B9%C9%94s%C9%90%
CA%8C%C9%90%C9%BE-%C9%B9%C7%9D%CA%8Dsu%C9%90-19a33b0a467d#.3yu73z1px
⁶https://en.wikipedia.org/wiki/ECMAScript
⁷http://kangax.github.io/compat-table/es6/
What you’ll need
TL;DR
• The easiest way to get your feet wet and code along is to use a JavaScript playground like
CodePen⁸.
• If you don’t have access to a reliable Internet connection, an alternative is to set up a
development machine with a code editor and a appropriate folder structure.
• In all cases, you’ll need the most recent version of a modern web browser.
Environment setup
Few things are more frustrating than starting to learn something new and then having to spend
hours trying to set up a proper work environment. Fortunately, one of the beauties of JavaScript
code is that it can run on almost any browser. We’ll be using this to our advantage throughout
this book. No complex setup requiring administrative rights on your machine: all you’ll need is
a modern browser and an active Internet connection (see below if you don’t have access to a
reliable connection or must work offline).
A browser is the software you use to visit webpages and use web applications. Check
the site whatbrowser.org⁹ for more info and advice about upgrading your browser.
This book targets a recent version of the JavaScript language. Whatever browser you choose to
use (or have access to), it’s important that you upgrade it to its most recent version.
Once your browser is updated, the quickest and easiest way to follow along is to use an
online JavaScript playground. My personal favorite is CodePen¹⁰, but there are alternatives like
JSFiddle¹¹ and JS Bin¹².
A JavaScript playground is an online service where you can type some JavaScript
code and immediatly visualize its result without any environment setup.
⁸http://codepen.io
⁹http://whatbrowser.org/
¹⁰http://codepen.io
¹¹https://jsfiddle.net/
¹²http://jsbin.com/
What you’ll need xii
CodePen 101
If you choose to use CodePen along with this book, you really should start by visiting Welcome
to CodePen¹³. It introduces the platform in a very friendly way and gives you everything you
need to get started.
In addition, there are some helpful articles in the CodePen documentation about autocomplete¹⁴,
the console¹⁵, pen autosaving¹⁶, keybindings¹⁷ and auto-updating¹⁸. Albeit not mandatory,
mastering CodePen will make you more productive while studying this book.
I advise you to enable autosave and disable auto-update for all your book-related pens.
Showing the CodePen console will often be needed to look at the results produced by
the code.
You should use a pen (not necessarily saved) to try every code sample this book contains. You
should also dedicate a specific and saved pen to each exercise you’ll search.
Working offline
Using CodePen or another JavaScript playground requires a reliable Internet connection. If that’s
not your case (or if you prefer/have to work offline), you’ll need to use a code editor on your
machine. Here are some of them:
¹³https://codepen.io/hello/
¹⁴https://blog.codepen.io/documentation/editor/autocomplete/
¹⁵https://blog.codepen.io/documentation/editor/console/
¹⁶https://blog.codepen.io/documentation/editor/autosave/
¹⁷https://blog.codepen.io/documentation/editor/key-bindings/
¹⁸https://blog.codepen.io/documentation/editor/auto-updating-previews/
What you’ll need xiii
To learn how to test JavaScript code locally and set up your machine with an appropriate folder
structure, follow these instructions²³.
¹⁹https://code.visualstudio.com/
²⁰http://brackets.io/
²¹https://atom.io/
²²https://www.sublimetext.com/
²³https://openclassrooms.com/courses/learn-the-basics-of-javascript/configure-your-work-environment#/id/r-3677157
I Learn to code programs
1. 3, 2, 1… Code!
Let’s get started! This chapter will introduce you to the fundamentals of programming including
values, types, and program structure.
TL;DR
• A value is a piece of information. The type of a value defines its role and the operations
applicable to it.
• The JavaScript language uses the number type to represent a numerical value (with or
without decimals) and the string type to represent text.
• A string value is surrounded by a pair of single quotes ('...') or a pair of quotation marks
("...").
• Arithmetic operations between numbers are provided by the +, -, * and / operators.
Applied to two strings, the + operators joins them together. This operation is called
concatenation.
• A computer program is made of several lines of code read sequentially during execution.
• Comments (// ... or /* ... */) are non-executed parts of code. They form a useful
program documentation.
• The JavaScript command console.log() displays a message.
This program displays the text "Hello from JavaScript!" in the console, a zone displaying
textual information available in most JavaScript environnements, such as browsers.
To achieve this, its uses a JavaScript command named console.log(), which role is to display a
piece of information. The text to be displayed is placed between parenthesis and followed by a
semicolon, which mark the end of the line.
Displaying a text on the screen (the famous Hello World¹ all programmers know) is often the first
thing you’ll do when you learn a new programming language. It’s the classic example. You’ve
already taken that first step!
¹https://en.wikipedia.org/wiki/Hello_world
3, 2, 1… Code! 3
Number
A number is a numerical value (thanks Captain Obvious). Let’s go beyond that though! Like
mathematics, you can use integer values (or whole numbers) such as 0, 1, 2, 3, etc, or real numbers
with decimals for greater accuracy.
Numbers are mainly used for counting. The main operations you’ll see are summarized in the
following table. All of them produce a number result.
Operator Role
+ Addition
- Substraction
* Multiplication
/ Division
String
A string in JavaScript is text surrounded by quotation marks, such as "This is a string".
You can also define strings with a pair of single quotes: 'This is another string'. The best
practice for single or double quotes is a whole political thing. Use whichever you like, but don’t
mix the two in the same program!
Always remember to close a string with the same type of quotation marks you started
it with.
To include special characters in a string, use the \ character (backslash) before the character. For
example, type \n to add a new line within a string: "This is\na multiline string".
You can not add or remove string values like you’d do with numbers. However, the + operator
has a special meaning when applied to two string values. It will join the two chains together,
and this operation is called a concatenation. For example, "Hel" + "lo" produces the result
"Hello".
Program structure
We already defined a computer program as a list of commands telling a computer what to do.
These orders are written as text files and make up what’s called the “source code” of the program.
The lines of text in a source code file are called lines of code.
3, 2, 1… Code! 4
The source code may include empty lines: these will be ignored when the program executes.
Statements
Each instruction inside a program is called a statement. A statement in JavaScript usually ends
with a semicolon (albeit it’s not strictly mandatory). Your program will be made up of a series
of these statements.
Execution flow
When a program is executed, the statements in it are “read” one after another. It’s the
combination of these individual results that produces the final result of the program.
Here’s an example of a JavaScript program including several statements.
Execution result
Comments
By default, each line of text in the source files of a program is considered a statement that should
be executed. You can prevent certain lines from executing by putting a double slash before them:
//. This turns the code into a comment.
During execution, the commented-out lines no longer produce results. As we hoped, they weren’t
executed.
Execution result
Comments are great for developers so you can write comments to yourself, explanations about
your code, and more, without the computer actually executing any of it.
You can also write comments by typing /* */ around the code you want commented out.
/* A comment
written on
several lines */
Comments are a great source of info about a program’s purpose or structure. Adding comments
to complicated or critical parts is a good habit you should build right now!
Coding time!
Let’s put your brand new coding skills into practice.
3, 2, 1… Code! 6
Presentation
Write a program that displays your name and age. Here’s the result for mine.
Minimalistic calculator
Writea a program that displays the results of adding, substracting, multiplicating and dividing 6
by 3.
Values prediction
Observe the following program and try to predict the values it displays.
console.log(4 + 5);
console.log("4 + 5");
console.log("4" + "5");
TL;DR
• A variable is an information storage area. Every variable has a name, a value and a type.
In JavaScript, the type of a variable is deduced from the value stored in it: JavaScript is a
dynamically typed language.
• A variable is declared using the let keyword followed by the variable name. To declare a
constant (a variable whose initial value must never change), it’s better to use the const
keyword instead.
• To give a value to a variable, we use the assignment operator =. For number variables,
the operators += and ++ can increment (increase by 1) their value.
• The scope of a variable is the part of the program where the variable is visible. Variables
declared with let or const are block-scoped. A code block is a portion of a program
delimited by a pair of opening and closing curly braces { ... }.
• An expression is a piece of code that combines variables, values and operators. Evaluating
an expression produces a value, which has a type.
• Expressions may be included in strings delimited by a pair of backticks (‘). Such a string
is called a template literal.
• Type conversions may happen implicitely during the evaluation of an expression, or
explicitely when using the Number() and String() commands, to obtain a respectively
a number or a string.
• The prompt() and alert() commands deal with information input and display under the
form of dialog boxes.
• Variable naming is essential to program lisibility. Following a naming convention like
camelCase¹ is good practice.
Variables
Role of a variable
A computer program stores data using variables. A variable is an information storage area. We
can imagine it as a box in which you can put and store things!
¹https://en.wikipedia.org/wiki/Camel_case
Play with variables 8
Variable properties
A variable has three main properties:
• Its name, which identifies it. A variable name may contain upper and lower case letters,
numbers (not in the first position) and characters like the dollar ($) or underscore (_).
• Its value, which is the data stored in the variable.
• Its type, which determines the role and actions available to the variable.
You don’t have to define a variable type explicitly in JavaScript. Its type is deduced
from the value stored in the variable and may change while the program runs. That’s
why we say that JavaScript is a dynamically typed language. Other languages, like C
or Java, require variable types to always be defined. This is called static typing.
Declaring a variable
Before you can store information in a variable, you have to create it! This is called declaring
a variable. Declaring a variable means the computer reserves memory in which to store the
variable. The program can then read or write data in this memory area by manipulating the
variable.
Here’s a code example that declares a variable and shows its contents:
let a;
console.log(a);
In JavaScript, you declare a variable with the let keyword followed by the variable name. In
this example, the variable created is called a.
In previous versions of the language, variables were declared using the var keyword.
Execution result
Note that the result is undefined. This is a special JavaScript type indicating no value. I declared
the variable, calling it a, but didn’t give it a value!
Play with variables 9
let a;
a = 3.14;
console.log(a);
Execution result
We modified the variable by assigning it a value. a = 3.14 reads as “a receives the value 3.14”.
Be careful not to confuse the assignment operator = with mathematical equality! You’ll
soon see how to express equality in JavaScript.
You can also combine declaring a variable and assigning it a value in one line. Just know that,
within this line, you’re doing two different things at once:
let a = 3.14;
console.log(a);
let b = 0; // b contains 0
b += 1; // b contains 1
b++; // b conttains 2
console.log(b); // Shows 2
Variable scope
The scope of a variable is the part of the program where the variable is visible and usable.
Variables declared with let or const are block-scoped: their visibility is limited to the
block where they are declared (and every sub-block, if any). In JavaScript and many other
programming languages, a code block is a portion of a program delimited by a pair of opening
and closing braces. By default, a JavaScript program forms one block of code.
let nb1 = 0;
{
nb1 = 1; // OK : nb1 is declared in the parent block
const nb2 = 0;
}
console.log(nb1); // OK : nb1 is declared in the current block
console.log(nb2); // Error! nb2 is not visible here
Expressions
An expression is a piece of code that produces a value. An expression is created by combining
variables, values and operators. Every expression has a value and thus a type. Calculating an
expression’s value is called evaluation. During evaluation, variables are replaced by their values.
Operator priority inside an expression is the same as in math. However, an expression can
integrate parenthesis that modify these priorities.
Play with variables 11
let e = 3 + 2 * 4; // e contains 11 (3 + 8)
e = (3 + 2) * 4; // e contains 20 (5 * 4)
It is possible to include expressions in a string by using backticks (‘) to delimitate the string.
Such a string is called a template literal. Inside a template literal, expressions are identified by
the ${expression} syntax.
This is often used to create strings containing the values of some variables.
Type conversions
An expression’s evaluation can result in type conversions. These are called implicit conversions,
as they happen automatically without the programmer’s intervention. For example, using the +
operator between a string and a number causes the concatenation of the two values into a string
result.
const f = 100;
// Show "Variable f contains the value 100"
console.log("Variable f contains the value " + f);
const g = "five" * 2;
console.log(g); // Show NaN
Sometimes you’ll wish to convert the value of another type. This is called explicit conversion.
JavaScript has the Number() and String() commands that convert the value between the
parenthesis to a number or a string.
const h = "5";
console.log(h + 1); // Concatenation: show the string "51"
const i = Number("5");
console.log(i + 1); // Numerical addition: show the number 6
User interactions
Entering information
Once you start using variables, you can write programs that exchange information with the user.
Play with variables 12
During execution, an dialog box pops up, asking for your name.
Execution result
This is the result of the JavaScript command prompt("Enter your first name:").
Type your name and click OK. You’ll then get a personalized greeting.
Execution result
The value you entered in the first dialog box has been stored as a string in the variable name. The
JavaScript command alert() then triggered the display of the second box, containing the result
of the concatenation of the string "Hello, " with the value of the name variable.
Displaying information
Both console.log() (encountered in the previous chapter) and alert() can be used to display
information to the user. Unlike alert(), console.log() does not stop program execution and is
often a better choice.
console.log() can also display several comma-separated values at once.
Play with variables 13
Entering a number
Regardless of the entered data, the prompt() command always return a string value. If this value
is to be used in numerical expressions, it must be converted into a number with the Number()
command.
Both operations can be combined in one line for the same result.
In this example, the user input is directly converted in a number value by the Number() command
and stored in the nb variable.
Variable naming
To close this chapter, let’s discuss variable naming. The computer doesn’t care about variable
names. You could name your variables using the classic example of a single letter (a, b, c…) or
choose absurd names like burrito or puppieskittens90210.
Nonetheless, naming variables well can make your code much easier to read. Check out these
two examples:
They function in the same way, but the second version is much easier to understand.
How are some good ways to name variables?
Play with variables 14
Like many other languages, JavaScript is case sensitive. For example, myVariable and
myvariable are two different variable names. Be careful!
Coding time!
Build a habit of choosing good variables name in all exercises, starting with these ones.
Improved hello
Write a program that asks the user for his first name and his last name. Th program then displays
them in one sentence.
Final values
Observe the following program and try to predict the final values of its variables.
²https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Keywords
³https://en.wikipedia.org/wiki/Camel_case
Play with variables 15
let a = 2;
a = a - 1;
a++;
let b = 8;
b += 2;
const c = a + b * b;
const d = a * b + b;
const e = a * (b + b);
const f = a * b / a;
const g = b / a * a;
console.log(a, b, c, d, e, f, g);
VAT calculation
Write a program that asks the user for a raw price. After that, its calculates the corresponding
final price using a VAT rate of 20.6%.
The conversion between scales is given by the formula: [°F] = [°C] x 9/5 + 32.
Variable swapping
Observe the following program.
let number1 = 5;
let number2 = 3;
Add the necessary code to swap the values of variables number1 and number2.
This exercise has several valid solutions. You may use more than two variables to solve
it.
3. Add conditions
Up until now, all the code in our programs has been executed chronologically. Let’s enrich our
code by adding conditional execution!
TL;DR
• The if keyword defines a conditional statement, also called a test. The associated code
block is only run if the condition is satisfied (its value is true). Thus, a condition is an
expression whose evaluation always produces a boolean result (true or false).
if (condition) {
// Code to run when the condition is true
}
• The code block associated to an if is delimited by a pair of opening and closing braces. To
improve lisibility, its statements are generally indented (shifted to the right).
• The comparison operators ===, !==, <, <=, > et >= are used to compare numbers inside a
condition. All of them return a boolean result.
• An else statement can be associated to an if to express an alternative. Depending on
the condition value, either the code block associated to the if or the one associated to the
else will be run, but never both. Thre is no limit to the depth of condition nesting.
if (condition) {
// Code to run when the condition is true
}
else {
// Code to run when the condition is false
}
• Complex conditions can be created using the logical operators && (“and”), || (“or”) et !
(“not”).
• The switch statement is used to kick off the execution of one code block among many,
depending on the value of an expression.
Add conditions 17
switch (expression) {
case value1:
// Code to run when the expression matches value1
break;
case value2:
// Code to run when the expression matches value2
break;
...
default:
// Code to run when neither case matches
}
What’s a condition?
Suppose we want to write a program that makes enter a number to the user, who then displays
a message if the number is positive. Here the corresponding algorithm.
Enter a number
Si the number is positive
Display a message
The message should display only if the number is positive: this means it’s “subject” to a
condition.
The if statement
Here’s how you translate the program to JavaScript.
The console.log(...) command is executed only if the number is positive. Test this program
to see for yourself!
Conditional syntax looks like this:
if (condition) {
// Code to run when the condition is true
}
Add conditions 18
The pair of opening and closing braces defines the block of code associated with an if statement.
This statement represents a test. It results in the following: “If the condition is true, then executes
the instructions contained in the code block”.
The condition is always placed in parentheses after the if. The statements within the associated
code block are shifted to the right. This practice is called indentation and helps make your code
more readable. As your programs grow in size and complexity, it will become more and more
important. The indentation value is often 2 or 4 spaces.
When the code block has only one statement, braces may be omitted. As a beginner,
you should nonetheless always use braces when writing your first conditions.
Conditions
A condition is an expression that evaluates as a value either true or false: it’s called a boolean
value. When the value of a condition is true, we say that this condition is satisfied.
We have already studied numbers and strings, two types of data in JavaScript. Booleans are
another type. This type has only two possible values: true and false.
Any expression producing a boolean value (either true or false) can be used as a condition in an
if statement. If the value of this expression is true, the code block associated with it is executed.
if (true) {
// The condition for this if is always true
// This block of code will always be executed
}
if (false) {
// The condition for this if is always false
// This block of code will never be executed
}
Boolean expressions can be created using the comparison operators shown in the following table.
Operator Meaning
=== Equal
!== Not equal to
< Less than
<= Less than or equal to
> Greater than
>= Greater than or equal to
In some other programming languages, equality and inequality operators are == and !=. They
also exist in JavaScript, but it’s safer to use === and !== (more details¹).
¹https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness
Add conditions 19
It’s easy to confuse comparison operators like === (or ==) with the assignment operator
=. They’re very, very different. Be warned!
Now let’s modify the example code to replace > with >= and change the message, then test it
with the number 0.
If the user input is 0, the message appears in the console, which means that the condition(number
>= 0) was satisfied.
Alternative conditions
You’ll often want to have your code execute one way when something’s true and another way
when something’s false.
Test this code with a positive number, negative number, and zero, while watching the result in
the console. The code executes differently depending if the condition (number > 0) is true or
false.
The syntax for creating an alternative is to add an else keyword after an initial if.
Add conditions 20
if (condition) {
// Code to run when the condition is true
}
else {
// Code to run when the condition is false
}
You can translate an if/else statement like this: “If the condition is true, then execute this first
set of code; otherwise, execute this next set of code”. Only one of the two code blocks will be
executed.
Nesting conditions
Let’s go next level and display a specific message if the entered number is zero. See this example,
which has a positive test case, negative test case, and a last resort of the number being zero.
Let’s wrap our heads around it. If the code block associated to the first else is run, then the
number has to be either strictly negative or zero. Inside this block, a second if statement checks
if the number is negative. If it’s not, we know for sure that it’s zero.
When learning to write nested conditions, you should add descriptive comments to
each condition, just like in the previous example.
The execution flow for the previous program can be expressed graphically using a flow diagram.
Add conditions 21
This example shows how essential indentation is for understanding a program’s flow. There is
no limit to the possible depth of condition nesting, but too many will affect program lisibility.
A particular case happens when the only statement in a else block is an if. In that case, you
can write this else on the same line as the if and without braces. Here’s a more concise way to
write our example program.
“And” operator
Suppose you want to check if a number is between 0 and 100. You’re essentially checking if it’s
“greater than or equal to 0” and “less than or equal to 100”. Both sub-conditions must be satisfied
at the same time.
Add conditions 22
The expression 0 <= nombre <= 100 is correct from a mathematical point of view but
cannot be written in JavaScript (neither in most other programming languages).
Parentheses between sub-conditions are not mandatory but I advise you to add them
anyway, to avoir nasty bugs in some special cases.
The && operator (“logical and”) can apply to both types of boolean values. true will only be the
result of the statement if both conditions are true.
“Or” operator
Now imagine you want to check that a number is outside the range of 0 and 100. To meet this
requirement, the number should be less than 0 or greater than 100.
Here it is, translated into JavaScript:
The || operator (“logical or”) makes statements true if at least one of the statements is true.
Here’s its truth table:
“Not” operator
There’s another operator for when you know what you don’t want: the not operator! You’ll use
a ! for this.
Add conditions 23
console.log(!true); // false
console.log(!false); // true
Multiple choices
Let’s write some code that helps people decide what to wear based on the weather using if/else.
When a program should trigger a block from several operations depending on the value of an
expression, you can write it using the JavaScript statement switch to do the same thing.
If you test it out, the result will be the same as the previous version.
The switch statement kicks off the execution of one code block among many. Only the code
block that matches the relevant situation will be executed.
switch (expression) {
case value1:
// Code to run when the expression matches value1
break;
case value2:
// Code to run when the expression matches value2
break;
...
default:
// Code to run when neither case matches
}
You can set as many cases as you want! The word default, which is put at the end of switch, is
optional. It can let you handle errors or unexpected values.
Adding a break; in each block is important so you get out of the switch statement!
const x = "abc";
switch (x) {
case "abc":
console.log("x = abc");
// break omitted: the next block is also run!
case "def":
console.log("x = def");
break;
}
The previous example show "x = abc" (the correct result) but also "x = def".
Coding time!
Here are a few advice about these exercises:
• Keep on choosing your variable names wisely, and respect indentation when creating code
blocks associated to if, else and switch statements.
• Try to find alternative solutions. For example, one using an if and another using a switch.
• Test your programs thoroughly, without fear of finding mistakes. It’s a very important
skill.
Add conditions 25
Following day
Write a program that accepts a day name from the user, then shows the name of the following
day. Incorrect inputs must be taken into account.
Number comparison
Write a program that accepts two numbers, then compare their values and displays an appropri-
ate message in all cases.
Final values
Take a look at the following program.
Before executing it, try to guess the final values of variables nb1, nb2 and nb3 depeding on their
initial values. Complete the following table.
Initial values nb1 final value nb2 final value nb3 final value
nb1=nb2=nb3=4
nb1=4,nb2=3,nb3=2
nb1=2,nb2=4,nb3=0
Following second
Write a program that asks for a time under the form of three informations (hours, minutes,
seconds). The program calculates and shows the time one second after. Incorrect inputs must be
taken into account.
This is not as simple as it seems… Look at the following results to see for yourself:
• 14h17m59s ⇒ 14h18m0s
• 6h59m59s ⇒ 7h0m0s
• 23h59m59s ⇒ 0h0m0s (midnight)
4. Repeat statements
In this chapter, we’ll look at how to execute code on a repeating basis.
TL;DR
• Loops are used to repeat a series of statements. Each repetition is called an iteration. The
code block associated to a loop is called its body.
• The while loop repeats statements while a certain condition is true. The for loop gives the
ability to manage what happens just before the loop starts and after each loop iteration
has run.
// While loop
while (condition) {
// Code to run while the condition is true
}
// For loop
for (initialization; condition; final expression) {
// code to run while the condition is true
}
• The variable associated to the loop condition is called the loop counter and often named
i.
• Beware! The condition of a while loop must eventually become false, to avoid the risk of
an infinite loop. Also, updating the counter of a for loop inside its body is a bad idea.
• All loops can be written with while, but if you know in advance how many times you
want the loop to run, for is the best choice.
Introduction
If you wanted to write code that displayed numbers between 1 and 5, you could do it with what
you’ve already learned:
Repeat statements 28
console.log(1);
console.log(2);
console.log(3);
console.log(4);
console.log(5);
This is pretty tiresome though and would be much more complex for lists of numbers between
1 and 1000, for example. How can you accomplish the same thing more simply?
JavaScript lets you write code inside a loop that executes repeatedly until it’s told to stop. Each
time the code runs, it’s called an iteration.
Example
Here’s a sample program written with a while loop.
let number = 1;
while (number <= 5) {
console.log(number);
number++;
}
Just like the previous one, it shows all integer numbers between 1 and 5.
Repeat statements 29
Execution result
How it works
You’ll use the following syntax to write a while loop.
while (condition) {
// Code to run while the condition is true
}
Before each loop iteration, the condition in parentheses is evaluated to determine whether it’s
true or not. The code associated with a loop is called its body.
• If the condition’s value is true, the code in the while loop’s body runs. Afterwards, the
condition is re-evaluated to see if it’s still true or not. The cycle continues!
• If the condition’s value is false, the code in the loop stops running or doesn’t run.
The loop body must be placed within curly braces, except if it’s only one statement.
For now, always use curly braces for your loops.
Example
Here’s the same program as above written instead with a for loop.
Repeat statements 30
let number;
for (number = 1; number <= 5; number++) {
console.log(number);
}
How it works
Here’s the for loop syntax.
• Initialization only happens once, when the code first kicks off. It’s often used to set the
initial value of the variable associated to the loop condition.
• The condition is evaluated once before the loop runs each time. If it’s true, the code runs.
If not, the code doesn’t run.
• The final expression is evaluated after the loop runs each time. It’s often used to update the
value of the variable associated to the loop condition, as we saw in the previous example.
Common mistakes
let number = 1;
while (number <= 5) {
console.log(number);
// The number variable is not updated: the loop condition stays true fore\
ver
}
To protect yourself from infinite loops, you have to make sure the loop condition will eventually
become false.
Execution result
Each time the loop runs, the counter variable is incremented twice: once in the body and once
in the final expression after the loop runs. When you’re using a for loop, you’ll almost always
want to omit anything to do with the counter inside the body of your loop. Just leave it in that
first line!
You can’t know how many times it’ll take for the user to enter X, so while is generally good for
loops that depend on user interaction.
Ultimately, choosing which loop to use depends on context. All loops can be written with while,
but if you know in advance how many times you want the loop to run, for is the best choice.
Coding time!
Yry to code each exercise twice, once with a while loop and the other with a for, to see for
yourself which one is the most appropriate.
Carousel
Write a program that launches a carousel for 10 turns, showing the turn number each time.
When it’s done, improve it so that the number of turns is given by the user.
Parity
Check the following program that shows even number (divisibles by 2) betwen 1 and 10.
This program uses the modulo operator %, which calculates the remainder after division of one
number by another. It’s often used to assess number parity.
Improve the program so that it also shows odd numbers. Improve it again so that the initial
number is given by the user.
This program must show exactly 10 numbers including the first one, not 11!
Repeat statements 33
Input validation
Write a program that asks the user for a number until it’s less than or equal to 100.
When it’s done, improve it so that the number is between 50 and 100.
Multiplication table
Write a program that asks the user for a number, then shows the multiplication table for this
number.
When it’s done, improve it to only accept numbers between 2 and 9 (use the previous exercise
as a blueprint).
FizzBuzz
Write a program that shows all numbers between 1 and 100 with the following exceptions:
When it’s done, improve it so that it shows "FizzBuzz" instead of numbers divisible both by 3
and by 5.
This exercise has many, many solutions¹. It’s a job interview classic² that a signifi-
cant number of candidates fail. Try your best!
¹http://www.tomdalling.com/blog/software-design/fizzbuzz-in-too-much-detail/
²http://imranontech.com/2007/01/24/using-fizzbuzz-to-find-developers-who-grok-coding/
5. Write functions
In this chapter, you’ll learn how to break down a program into subparts called functions.
TL;DR
• A function is a group of statements that performs a particular task. JavaScript functions
are created using the function keyword.
• Written as a combinaison of several short and focused functions, a program will generally
be easier to understand and more modular than a monolitic one.
• A function call triggers the execution of the function code. After it’s done, execution
resumes at the place where the call was made.
• Variables declared inside a function are limited in scope to the function body. They are
called local variables.
• A return statement inside the function body defines the return value of the function. A
function can accept zero, one or several parameters in order to work. For a particular call,
supplied parameter values are called arguments.
• There are several ways to create a function in JavaScript. A first one is to use a function
declaration.
// Function declaration
function myFunction(param1, param2, ...) {
// Function code using param1, param2, ...
}
// Function call
myFunction(arg1, arg2, ...);
// Function call
myVar(arg1, arg2, ...);
• A third way to create an anonymous function is the more recent fat arrow syntax.
// Function call
myVar(arg1, arg2, ...);
• No matter how it’s created, each function should have a precise purpose and a well chosen
name (often including an action verb). JavaScript offers a lots a predefined functions
covering various needs.
Begin
Get out the rice cooker
Fill it with rice
Fill it with water
Cook the rice
Chop the vegetables
Stir-fry the vegetables
Taste-test the vegetables
If the veggies are good
Remove them from the stove
If the veggies aren't good
Add more pepper and spices
If the veggies aren't cooked enough
Keep stir-frying the veggies
Heat the tortilla
Write functions 36
Begin
Cook rice
Stir-fry vegetables
Add fillings
Roll together
End
The first version details all the individual actions that make up the cooking process. The second
breaks down the recipe into broader steps and introduces concepts that could be re-used for
other dishes as well like cook, stir-fry, add and roll.
Our programs so far have mimicked the first example, but it’s time to start modularizing our
code into sub-steps so we can re-use bits and pieces as needed. In JavaScript, these sub-steps are
called functions!
Discovering functions
A function is a group of statements that performs a particular task.
Here’s a basic example of a function.
function sayHello() {
console.log("Hello!");
}
console.log("Start of program");
sayHello();
console.log("End of program");
Write functions 37
Execution result
Declaring a function
Check out the first lines of the example above.
function sayHello() {
console.log("Hello!");
}
This creates a function called sayHello(). It consists of only one statement that will make a
message appear in the console: "Hello!".
This is an example of a function declaration.
The declaration of a function is performed using the JavaScript keyword function, followed by
the function name and a pair of parentheses. Statements that make up the function constitute
the body of the function. These statements are enclosed in curly braces and indented.
Calling a function
Functions must be called in order to actually run. Here’s the second part of our example program.
console.log("Start of program");
sayHello();
console.log("End of program");
The first and third statements explicitly display messages in the console. The second line makes
a call to the function sayHello().
You can call a function by writing the name of the function followed by a pair of parentheses.
Write functions 38
// ...
myFunction(); // Call myFunction
// ...
Calling a function triggers the execution of actions listed therein (the code in its body). After it’s
done, execution resumes at the place where the call was made.
Usefulness of functions
A complex problem is generally more manageable when broken down in simpler subproblems.
Computer programs are no exception to this rule. Writen as a combinaison of several short and
focused functions, a program will be easier to understand and to update than a monolitic one.
As an added bonus, some functions could be reused in other programs!
Creating functions can also be a solution to the problem of code duplication¹: instead of being
duplicated at several places, a piece of code is centralized in a function and called from anywhere
when needed.
¹https://en.wikipedia.org/wiki/Duplicate_code
Write functions 39
Function contents
Return value
Here is a variation of our example program.
function sayHello() {
return "Hello!";
}
console.log("Start of program");
const message = sayHello(); // Store the function return value in a variable
console.log(message); // Show the return value
console.log("End of program");
Run this code, and you’ll see the same result as before.
In this example, the body of the sayHello() function has changed: the statement console.log("Hello!")
was replaced by return "Hello!".
The keyword return indicates that the function will return a value, which is specified immedi-
ately after the keyword. This return value can be retrieved by the caller.
// Declare myFunction
function myFunction() {
let returnValue;
// Calculate return value
// returnValue = ...
return returnValue;
}
This return value can be any type (number, string, etc). However, a function can return only one
value.
Retrieving a function’s return value is not mandatory, but in that case the return value
is “lost”.
If you try to retrieve the return value of a function that does not actually have one, we get the
JavaScript value undefined.
Write functions 40
function myFunction() {
// ...
// No return value
}
A function stops running immediately after the return statement is executed. Any
further statements would never be run.
Let’s simplify our example a bit by getting rid of the variable that stores the function’s return
value.
function sayHello() {
return "Hello!";
}
console.log(sayHello()); // "Hello!"
The return value of the sayHello() function is directly output through the console.log()
command.
Local variables
You can declare variables inside a function, as in the example below.
function sayHello() {
const message = "Hello!";
return message;
}
console.log(sayHello()); // "Hello!"
The function sayHello() declares a variable named message and returns its value.
The variables declared in the body of a function are called local variables. Their scope is limited
to the function body (hence their name). If you try to use it outside the function, you won’t be
able to!
Write functions 41
function sayHello() {
const message = "Hello!";
return message;
}
console.log(sayHello()); // "Hello!"
console.log(message); // Error: the message variable is not visible here
Each function call will redeclare the function’s local variables, making the calls perfectly
independent from one another.
Not being able to use local variables outside the functions in which they are declared may seem
like a limitation. Actually, it’s a good thing! This means functions can be designed as autonomous
and reusable. Moreover, this prevents naming conflicts: variables declared in different functions
may have the same name.
Parameter passing
A parameter is an information that the function needs in order to work. The function parameters
are defined in parentheses immediately following the name of the function. You can then use
the parameter value in the body of the function.
You supply the parameter value when calling the function. This value is called an argument.
Let’s edit the above example to add a personalized greeting:
function sayHello(name) {
const message = `Hello, ${name}!`;
return message;
}
The declaration of the sayHello() function now contains a parameter called name.
In this example, the first call to sayHello() is done with the argument "Baptiste" and the second
one with the argument "Thomas". In the first call, the value of the name parameter is "Baptiste",
and "Thomas" in the second.
Here’s the general syntax of a function declaration with parameters. The number of parameters
is not limited, but more than 3 or 4 is rarely useful.
Write functions 42
// Function call
// param1 value is set to arg1, param2 to arg2, ...
myFunction(arg1, arg2, ...);
Just like with local variables, parameter scope is limited to the function body. Thus, an external
variable used as an argument in a function call may have the same name as a function parameter.
The following example is perfectly valid.
function sayHello(name) {
// Here, "name" is the function parameter
const message = `Hello, ${name}!`;
return message;
}
When calling a function, respecting the number and order of parameters is paramount! Check
out the following example.
The second call arguments are given in reverse order, so name gets the value 5 and age gets
"Prosper" for that call.
Anonymous functions
Declaration is not the only way to create functions in JavaScript. Check out this example.
Write functions 43
In this example, the function is assigned to the hello variable. The value of this variable is a
function. We call the function using that variable. This is an example of a function expression.
A function expression defines a function as part of a larger expression, typically a variable
assignment.
The function created in this example has no name: it is anonymous. As you’ll soon discover,
anonymous functions are heavily used in JavaScript.
Here’s how to create an anonymous function and assign it to a variable.
Recent language evolutions have introduced a more concise way to create anonymous functions:
Fat arrow function syntax can be further simplified in some particular cases:
• When there’s only one statement in the function body, everything can be written on the
same line without curly braces. The return statement is omitted and implicit.
• When the function accepts only one parameter, parentheses around it can be omitted.
Functions are a core part of the JavaScript toolset. You’ll use them non-stop in your programs.
The function Math.min() return the minimum number among its arguments. The function
Math.random() generates a random number betwen 0 and 1.
This book will introduce many other JavaScript functions.
If you have difficulties coming up with a right name for a function, then maybe its
purpose is not that clear and you should ask yourself if this function deserves to exist.
Coding time!
Improved hello
Complete the following program so that it asks the user for his first and last names, then show
the result of the sayHello() function.
Number squaring
Complete the following program so that the square1() and square2() functions work properly.
²https://en.wikipedia.org/wiki/Camel_case
Write functions 46
When it’s done, update the program so that it shows the square of every number between 0 en
10.
Writing 10 dumb calls to square() is forbidden! You know how to repeat statements,
don’t you ? ;)
Calculator
Complete the following program so that it offers the four basic arithmetical operations: addition,
substration, multiplication and division. You can use either a function declaration or a function
expression.
Write functions 47
Circumference and area calculation formulas should be part of your school years
memories… Or a Google click away :)
TL;DR
• A JavaScript object is an entity that has properties. Each property is a key/value pair. The
key is the property name.
• The value of a property can be an information (number, string, etc) or a function. In that
case, the property is called a method.
• A JavaScript object literal is created by simply setting its properties within a pair of curly
braces.
const myObject = {
property1: value1,
property2: value2,
// ... ,
method1(/* ... */) {
// ...
},
method2(/* ... */) {
// ...
},
// ...
};
• Inside a method, the this keyword represents the object on which the method is called.
• The JavaScript language predefines many useful objects like console or Math.
Introduction
What’s an object?
Think about objects in the non-programming sense, like a pen. A pen can have different ink
colors, be manufactured by different people, have a different tip, and many other properties.
Create your first objects 49
Similarly, an object in programming is an entity that has properties**. Each property defines a
characteristic of the object. A property can be a information associated with the object (the color
of the pen) or an action (the pen’s ability to write).
Creating an object
Here is the JavaScript representation of a blue Bic ballpoint pen.
const pen = {
type: "ballpoint",
color: "blue",
brand: "Bic"
};
A JavaScript object can be created by simply setting its properties within a pair of curly braces:
{...}. Each property is a key/value pair. This is called an object literal.
The semicolon ; after the closing brace is optional, but it’s safer to add it anyway.
The above code defines a variable named pen whose value is an object: you can therefore say
pen is an object. This object has three properties: type, color and brand. Each property has a
name and a value and is separated by a comma , (except the last one).
¹https://en.wikipedia.org/wiki/Procedural_programming
Create your first objects 50
const pen = {
type: "ballpoint",
color: "blue",
brand: "Bic"
};
console.log(pen.type); // "ballpoint"
console.log(pen.color); // "blue"
console.log(pen.brand); // "Bic"
Accessing an object’s property is an expression that produces a value. Such an expression can
be included in more complex ones. For example, here’s how to show our pen properties in one
statement.
const pen = {
type: "ballpoint",
color: "blue",
brand: "Bic"
};
Execution result
Modifying an object
Once an object is created, you can change the value of its properties with the syntax myOb-
ject.myProperty = newValue.
const pen = {
type: "ballpoint",
color: "blue",
brand: "Bic"
};
Execution result
JavaScript even offers the ability to dynamically add new properties to an already created object.
const pen = {
type: "ballpoint",
color: "blue",
brand: "Bic"
};
Execution result
• his name,
• his health (number of life points),
• his strength.
A naive example
Let me introduce you to Aurora, our first RPG character.
const aurora = {
name: "Aurora",
health: 150,
strength: 25
};
The aurora object has three properties: name, health and strength.
As you can see, you can assign numbers, strings, and even other objects to properties!
Create your first objects 53
Aurora is about to start a series of great adventures, some of which will update her attributes.
Check out the following example.
const aurora = {
name: "Aurora",
health: 150,
strength: 25
};
Execution result
Introducing methods
In the above code, we had to write lengthy console.log statements each time to show our
character state. There’s a cleaner way to accomplish this.
const aurora = {
name: "Aurora",
health: 150,
strength: 25
};
console.log(describe(aurora));
Execution result
The describe() function takes an object as a parameter. It accesses that object’s properties to
create a description string.
Now for an alternative approach: creating a describe() property inside the object.
const aurora = {
name: "Aurora",
health: 150,
strength: 25,
console.log(aurora.describe());
Create your first objects 55
Execution result
Now our object has a new property available to it: describe(). The value of this property is a
function that returns a textual description of the object. The execution result is exactly the same
as before.
An object property whose value is a function is called a method. Methods are used to define
actions for an object. A method add some behavior to an object.
console.log(aurora.describe());
To show the character description, we use the aurora.describe() expression instead of de-
scribe(aurora). It makes an essential difference:
• describe(aurora) calls the describe() function with the aurora object as an argument.
The function is external to the object. This is an example of procedural programming.
• aurora.describe() calls the describe() function on the aurora object. The function
is one of the object’s properties: it is a method. This is an example of object-oriented
programming.
const aurora = {
name: "Aurora",
health: 150,
strength: 25,
You see a new keyword: this. This is automatically set by JavaScript inside a method and
represents the object on which the method was called.
The describe() method doesn’t take any parameters. It uses this to access the properties of the
object on which it is called.
• The console object gives access to the environment console. console.log() is actually a
method call.
• The Math object contains many mathematical properties. For example, Math.PI returns an
approximate value of the number π (Pi) and the Math.random() function returns a random
number between 0 and 1.
Coding time!
console.log(aurora.describe());
Execution result
Modeling a dog
Complete the following program to add the dog object definition.
Execution result
Modeling a circle
Complete the following program to add the circle object definition. Its radius value is input by
the user.
Create your first objects 58
Use this object to show its description, crediting 250, debiting 80, then show its description again.
Execution result
7. Store data in arrays
This chapter will introduce you to arrays¹, a type of variable used in many computer programs
to store data.
TL;DR
• An array represents a set of elements. A JavaScript array is an object that has special
properties, like length to access its size (number of elements).
• You can think of an array as a set of boxes, each storing a specific value and associated
with a number called its index. The first element of an array will be index number 0 - not
1.
• You can access a particular element by passing its index within square brackets [].
• To iterate over an array (browsing it element by element), you can use the for loop, the
forEach() method or the newer for-of loop.
myArray.forEach(myElement => {
// Use myElement to access each array element one by one
});
Introduction to arrays
Imagine you want to create a list of all the movies you’ve seen this year.
One solution would be to create several variables:
¹https://en.wikipedia.org/wiki/Array_data_type
Store data in arrays 60
If you’re a movie buff, you may find yourself with too many variables in your program. The
worst part is that these variables are completely independent from one another.
Another possibility is to group the movies in an object.
const movies = {
movie1: "The Wolf of Wall Street",
movie2: "Zootopia",
movie3: "Babysitting",
movie4: "Metropolis",
movie5: "Gone with the Wind",
// ...
};
This time, the data is centralized in the object movies. The names of its properties (movie1,
movie2, movie3…) are, however, unnecessary and repetitive.
You need a solution to store items together without naming them individually!
Luckily, there is one: use an array. An array is a data type that can store a set of elements.
Creating an array
Here’s how to create our list of movies in the form of an array.
An array is created with a pair of square brackets []. Everything within the brackets makes up
the array.
You can store different types of elements within an array, including strings, numbers, booleans
and even objects.
Store data in arrays 61
Since an array may contain multiple elements, it’s good to name the array plurally (for
example, movies).
You access the size of an array via its length property, using the dot notation.
Of course, this length property returns 0 in case of an empty array.
You can access a particular element by passing its index within square brackets []:
Store data in arrays 62
Using an invalid index to access a JavaScript array element returns the value undefined.
The for loop runs through each element in the array starting with index 0 all the way up to the
length of the array minus 1, which will be its last element.
Another way is to call the forEach() method on the array. It takes as a paramater a function
that will be applied to each array element.
Here’s the previous example, rewritten with this method and a fat arrow function.
During execution, each array element is passed as a parameter (named movie in this example)
to the anonymous function associated to forEach().
Lastly, you can use the for-of loop, a special kind of loop dealing with iterable objects² like
arrays. Here’s its syntax.
²https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#iterable
Store data in arrays 63
You add a new item to an array with the push() method. The new element to be added is passed
as a parameter to the method. It is inserted at the end of the array.
Alternatively, you can use the splice() method with two parameters: the first one is the index
from which to begin removing, and the second one is the number of elements to remove.
Store data in arrays 64
More on Arrays
You can do many wonderful things with arrays. Here are some links that may help you deepen
your understanding of arrays:
Coding time!
Create all these programs in a generic fashion: the program output should reflect any update in
the array’s content.
Musketeers
Write a program that:
• Creates an array named musketeers containing values “Athos”, “Porthos” and “Aramis”.
• Shows each array element using a for loop.
• Adds the “D’Artagnan” value to the array.
• Shows each array element using the forEach() method.
• Remove poor Aramis.
• Shows each array element using a for-of loop.
Sum of values
Write a program that creates the following array, then calculates and shows the sum of its values
(42 in that case).
³https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array
⁴https://www.w3schools.com/js/js_arrays.asp
⁵https://www.w3schools.com/js/js_array_methods.asp
⁶https://www.w3schools.com/jsref/jsref_obj_array.asp
Store data in arrays 65
Array maximum
Write a program that creates the following array, then calculates and shows its maximum value.
List of words
Write a program that asks the user for a word until he types "stop". The program then shows
each of these words, except "stop".
8. Work with strings
A lot of code you write will involve modifying chains of text characters - or strings¹. Let’s look
at how!
TL;DR
• Although string values are primitive JavaScript types, some properties and methods may
be applied to them just as if they were objects.
• The length property returns the number of characters of the string.
• JavaScript string are immutable²: once created, a string value never changes. String
methods never affect the initial value and always return a new string.
• The toLowerCase() and toUpperCase() methods respectively convert strings to lower and
upper case.
• String values may be compared using the === operator, which is case sensitive.
• A string may be seen as an array of characters identified by their index. The index of the
first character is 0 (not 1).
• You may iterate over a string using either a for or the newer for-of loop.
• Searching for values inside a string is possible with the indexOf(), startsWith() and
endsWith() methods.
• The split() method breaks a string into subparts delimited by a separator.
String recap
Let’s recapitulate what we already know about strings:
console.log("ABC".length); // 3
const m = "I am a string";
const l = m.length;
console.log(l); // 13
Although string values are primitive JavaScript types, some properties and methods can be
applied to them just as if they were objects by using the dot notation. length is one of those
properties.
toLowerCase() and toUpperCase() are two string methods. Like every string method, both have
no affect on the initial value and return a new string.
It’s important to understand that once created, a string value never change: strings are
immutable in JavaScript.
String comparison is case sensitive. Do pay attention to your lower and uppercase
letters!
Work with strings 68
Trying to access a string character beyond the string length produces an undefined
result.
This is impractical if your string contains more than a few characters. You need a better solution
to repeat access to characters. Does the word “repeat” bring to mind a former concept? Loops,
of course!
You may write a loop to access each character of a string. Generally speaking, a for loop is
a better choice than a while loop, since we know here that the loop will need to run for each
character in the string.
Work with strings 69
The loop counter i ranges from 0 (the index of the string’s first character) to string length - 1
(index of the last character). When the counter value equals the string length, the expression
becomes false and the loop ends.
So, the previous example may also be written with a for for an identical result.
Recent JavaScript evolution has introduced yet another option to iterate over a string: the for-of
loop. The previous example may also be written:.
If the index is not needed inside the loop, this syntax is arguably the simplest one.
When searching for a value at the beginning or end of a string, you may also use the
startsWith() and endsWith() methods. Both return either true or false, depending on whether
the value is found or not.
Work with strings 70
console.log(song.startsWith("Honk")); // true
console.log(song.startsWith("Tonk")); // false because of case sensitivity
console.log(song.endsWith("men")); // true
console.log(song.endsWith("Men")); // false because of case sensitivity
More on Strings
• Mozilla Developer Network JavaScript Reference: String³
• W3 Schools Strings⁴
• W3 Schools String Methods⁵
• W3 Schools String Reference⁶
• Quirksmode Strings⁷
Coding time!
Word info
Write a program that asks you for a word then shows its length, lowercase and uppercase values.
Vowel count
Improve the previous program so that it also shows the number of vowels inside the word.
³https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String
⁴https://www.w3schools.com/js/js_strings.asp
⁵https://www.w3schools.com/js/js_string_methods.asp
⁶https://www.w3schools.com/jsref/jsref_obj_string.asp
⁷http://www.quirksmode.org/js/strings.html
Work with strings 71
Backwards word
Improve the previous program so that it shows the word written backwards.
Palindrome
Improve the previous program to check if the word is a palindrome. A palindrome is a word or
sentence that’s spelled the same way both forward and backward, ignoring punctuation, case,
and spacing. Punctuation and spacing may not be taken into account here.
TL;DR
• Object-Oriented Programming, or OOP, is a programming paradigm¹ that uses objects
containing both data and behavior to create programs.
• A class is an object-oriented abstraction for an idea or a concept manipulated by a
program. It offers a convenient syntax to create objects representing this concept.
• A JavaScript class is defined with the class keyword. It can only contain methods. The
constructor() method, called during object creation, is used to initialize the object, often
by giving it some data properties. Inside methods, the this keyword represents the object
on which the method was called.
class MyClass {
constructor(param1, param2, ...) {
this.property1 = param1;
this.property2 = param2;
// ...
}
method1(/* ... */) {
// ...
}
method2(/* ... */) {
// ...
}
// ...
}
• Objects are created from a class with the new operator. It calls the class constructor to
initialize the newly created object.
¹https://en.wikipedia.org/wiki/Programming_paradigm
Understand object-oriented programming 73
• JavaScript’s OOP model is based on prototypes. Any JavaScript object has an internal
property which is a link (a reference) to another object: its prototype. Prototypes are used
to share properties and delegate behavior between objects.
• When trying to access a property that does not exist in an object, JavaScript tries to find
this property in the prototype chain of this object: its prototype, then its prototype’s own
prototype, and so on.
• There are several ways to create and link JavaScript objects through prototypes. One is to
use the Object.create() method.
• The JavaScript class syntax is another, arguably more convenient way to create relation-
ships between objects. It emulates the class-based OOP model found in languages like C++,
Java or C#. It is, however, just syntactic sugar on top of JavaScript’s own prototype-based
OOP model.
const aurora = {
name: "Aurora",
health: 150,
strength: 25,
xp: 0,
console.log(aurora.describe());
To make the game more interesting, we’d like to have more characters in it. So here comes
Glacius, Aurora’s fellow.
const glacius = {
name: "Glacius",
health: 139,
strength: 30,
xp: 0,
Our two characters are strikingly similar. They share the same properties, with the only
difference being some property values.
You should already be aware that code duplication is dangerous and should generally be avoided.
We must find a way to share what’s common to our characters.
JavaScript classes
Most object-oriented languages use classes as abstractions for the ideas or concepts manipulated
by a program. A class is used to create objects representing a concept. It offers a convenient
syntax to give both data and behavior to these objects.
JavaScript is no exception and supports programming with classes (but with a twist – more on
that later).
Creating a class
Our example RPG deals with characters, so let’s create a Character class to express what a
character is.
Understand object-oriented programming 75
class Character {
constructor(name, health, strength) {
this.name = name;
this.health = health;
this.strength = strength;
this.xp = 0; // XP is always zero for new characters
}
// Return the character description
describe() {
return `${this.name} has ${this.health} health points, ${this.strength} a\
s strength and ${this.xp} XP points`;
}
}
• A class is created with the class keyword, followed by the name of the class (usually
starting with a uppercase letter).
• Contrary to object literals, there is no separating punctuation between the elements inside
a class.
• A class can only contains methods, not data properties.
• Just like with object literals, the this keyword is automatically set by JavaScript inside a
method and represents the object on which the method was called.
• A special method named constructor() can be added to a class definition. It is called
during object creation and is often used to give it data properties.
Using a class
Once a class is defined, you can use it to create objects. Check out the rest of the program.
console.log(aurora.describe());
console.log(glacius.describe());
Understand object-oriented programming 76
Execution result
The aurora and glacius objects are created as characters with the new operator. This statement
calls the class constructor to initialize the newly created object. After creation, an object has
access to the properties defined inside the class.
Here’s the canonical syntax for creating an object using a class.
class MyClass {
constructor(param1, param2, ...) {
this.property1 = param1;
this.property2 = param2;
// ...
}
method1(/* ... */) {
// ...
}
method2(/* ... */) {
// ...
}
// ...
}
property that does not exist in an object, JavaScript tries to find this property in the prototype of
this object.
Here’s an example (borrowed from Kyle Simpson’s great book series You Don’t Know JS²).
const anObject = {
myProp: 2
};
console.log(anotherObject.myProp); // 2
In this example, the JavaScript statement Object.create() is used to create the object another-
Object with object anObject as its prototype.
When the statement anotherObject.myProp is run, the myProp property of anObject is used
since myProp doesn’t exist in anotherObject.
If the prototype of an object does not have a desired property, then research continues in its own
prototype until we get to the end of the prototype chain. If the end of this chain is reached
without having found the property, access to it returns the value undefined.
const anObject = {
myProp: 2
};
This type of relationship between JavaScript objects is called delegation: an object delegates part
of its operation to its prototype.
²https://github.com/getify/You-Dont-Know-JS/blob/master/this%20%26%20object%20prototypes/ch5.md
Understand object-oriented programming 78
The usefulness of the class syntax is a pretty heated debate in the JavaScript
community.
Object-oriented programming
Now back to our RPG, which is still pretty boring. What does it lack? Monsters and fights, of
course!
Here’s how a fight will be handled: if attacked, a character sees their life points decrease from
the strength of the attacker. If its health value fall below zero, the character is considered dead
and cannot attack anymore. Its vanquisher receives a fixed number of 10 experience points.
First, let’s add the possibility for our characters to fight one another. Since it’s a shared ability,
we define it as a method named attack() in the Character class.
class Character {
constructor(name, health, strength) {
this.name = name;
this.health = health;
this.strength = strength;
this.xp = 0; // XP is always zero for new characters
}
// Attack a target
attack(target) {
if (this.health > 0) {
const damage = this.strength;
console.log(`${this.name} attacks ${target.name} and causes ${damage} d\
amage points`);
³https://en.wikipedia.org/wiki/Syntactic_sugar
Understand object-oriented programming 79
target.health -= damage;
if (target.health > 0) {
console.log(`${target.name} has ${target.health} health points left`);
} else {
target.health = 0;
const bonusXP = 10;
console.log(`${this.name} eliminated ${target.name} and wins ${bonusX\
P} experience points`);
this.xp += bonusXP;
}
} else {
console.log(`${this.name} can't attack (they've been eliminated)`);
}
}
// Return the character description
describe() {
return `${this.name} has ${this.health} health points, ${this.strength} a\
s strength and ${this.xp} XP points`;
}
}
Now we can introduce a monster in the game and make it fight our players. Here’s the rest of
the final code of our RPG.
monster.attack(aurora);
monster.attack(glacius);
aurora.attack(monster);
glacius.attack(monster);
console.log(aurora.describe());
console.log(glacius.describe());
Understand object-oriented programming 80
Execution result
The previous program is a short example of Object-Oriented Programming (in short: OOP),
a programming paradigm⁴ (a programming style) based on objects containing both data and
behavior.
⁴https://en.wikipedia.org/wiki/Programming_paradigm
Understand object-oriented programming 81
Coding time!
Dogs
Complete the following program to add the definition of the Dog class.
Dogs taller than 60 make "Grrr! Grrr!" when they bark, other ones make "Woof!
Woof!".
Execution result
Character inventory
Improve the example RPG to add character inventory management according to the following
rules:
Execution result
Account list
Let’s build upon a previous account object exercise. A bank account is still defined by:
• A name property.
• A balance property, initially set to 0.
• A credit method adding the value passed as an argument to the account balance.
• A describe method returning the account description.
Understand object-oriented programming 83
Write a program that creates three accounts: one belonging to Sean, another to Brad and the
third one to Georges. These accounts are stored in an array. Next, the program credits 1000 to
each account and shows its description.
Execution result
10. Discover functional
programming
Object-oriented programming, albeit quite popular, is not the only way to create programs. This
chapter will introduce you to another important paradigm: functional programming.
TL;DR
• Functional programming is about writing programs by combining functions expressing
what the program should do, rather than how to do it (which is the imperative way).
• The state of a program is the value of its global variables at a given time. A goal of
functional programming is to minimize state mutations (changes) that make the code
harder to understand. Some possible solutions are declaring variables with const instead
of let, splitting the code into functions and favor local variables over global ones.
• A pure function depends solely in its inputs for computing its outputs and has no side
effect. Pure functions are easier to understand, combine together, and debug. Functional
programming favors the use of pure functions whenever possible.
• The map(), filter() and reduce() methods can replace loops for array traversal and let
you program with arrays in a functional way.
• JavaScript functions can be passed around just like any other value: they are first-class
citizens, enabling functional programming. A function that operates on another function
(taking it as an parameter or returning it) is called an higher-order function.
• JavaScript is a multi-paradigm language: you can write programs using an imperative,
object-oriented or functional programming style.
const movieList = [{
title: "Batman",
year: 1989,
director: "Tim Burton",
imdbRating: 7.6
}, {
title: "Batman Returns",
year: 1992,
director: "Tim Burton",
imdbRating: 7.0
}, {
title: "Batman Forever",
year: 1995,
director: "Joel Schumacher",
imdbRating: 5.4
}, {
title: "Batman & Robin",
year: 1997,
director: "Joel Schumacher",
imdbRating: 3.7
}, {
title: "Batman Begins",
year: 2005,
director: "Christopher Nolan",
imdbRating: 8.3
}, {
title: "The Dark Knight",
year: 2008,
director: "Christopher Nolan",
imdbRating: 9.0
}, {
title: "The Dark Knight Rises",
year: 2012,
director: "Christopher Nolan",
imdbRating: 8.5
}];
And here is the rest of the program that uses this data to show some results about the movies.
Check it out, it should be pretty self-explanatory.
Discover functional programming 86
Execution result
Discover functional programming 87
Program state
The previous program is an example of what is called imperative programming. In this
paradigm, the programmer gives orders to the computer through a series of statements that
modify the program state. Imperative programming focuses on describing how a program
operates.
The concept of state is an important one. The state of a program is the value of its global
variables (variables accessible everythere in the code) at a given time. In our example, the values
of movieList, titles, nolanMovieCount, bestTitles, ratingSum and averageRating form the
state of the program. Any assignment to one of these variables is a state change, often called a
mutation.
In imperative programming, the state can be modified anywhere in the source code. This is
convenient, but can also lead to nasty bugs and maintenance headaches. As the program grows
in size and complexity, it’s becoming easier for the programmer to mutate a part of the state by
mistake, and harder to monitor state modifications.
const n = 10;
const fruit = "Banana";
const obj = {
myProp: 2
};
const animals = ["Elephant", "Turtle"];
n++; // Illegal
fruit = "orange"; // Illegal
obj = {}; // Illegal
animals = ["Bee"]; // Illegal
console.log(titles());
nolanMovies();
console.log(nolanMovieList.length);
console.log(bestTitles());
Discover functional programming 89
console.log(averageNolanRating());
The state of our program is now limited to two variables: movieList and nolanMovieList
(the latter being necessary in functions nolanMovies() and averageNolanRating()). The other
variables are now local to the functions they are used into, which limit the possibility of an
accidental state mutation.
Also, this version of the program is easier to understand than the previous one. Functions with
appropriate names help describe a program’s behavior. Comments are now less necessary than
before.
Pure functions
Merely introducing some functions in a program is not enough to follow the functional
programming paradigm. Whenever possible, we also need to use pure functions.
A pure function is a function has the following characteristics:
A side effect is a change in program state or an interaction with the outside world. A database
access or a console.log() statement are examples of side effects.
Given the same data, a pure function will always produce the same result. By design, a pure
function is independent from the program state and must not access it. Such a function must
accept parameters in order to do something useful. The only way for a function without
parameters to be pure is to return a constant value.
Pure functions are easier to understand, combine together, and debug: contrary to their impure
counterparts, there’s no need to look outside the function body to reason about it. Still, a number
of side effects are necessary in any program, like showing output to the user or updating a
database. In functional programming, the name of the game is to create those side effects only
in some dedicated and clearly identified parts of the program. The rest of the code should be
written as pure functions.
Let’s refactor our example code to introduce pure functions.
console.log(titles(movieList));
const nolanMovieList = nolanMovies(movieList);
console.log(nolanMovieList.length);
console.log(bestTitles(movieList));
console.log(averageRating(nolanMovieList));
Array operations
Functional programming is about writing programs by combining functions expressing what the
program should do, rather than how to do it. JavaScript offers several array-related methods that
favor a functional programming style.
Here’s how our titles() could be rewritten using map(). Look how the function code is now
more concise and expressive.
The map() and filter() method can be used together to achieve powerful effects. Look at this
new version of the bestTitles() function.
• The first one is the function associated to reduce() and called for each array element
takes two parameters: the first is an accumulator which contains the accumulated value
previously returned by the last invocation of the function. The other function parameter
is the array element.
• The second one is the initial value of the accumulator (often 0).
Here’s how to apply reduce() to caculate the average rating of a movie list.
Another possible solution is to compute the rating sum by using map() before reducing an array
containing only movie ratings.
Discover functional programming 94
// ...
// Compute the sum of all movie IMDB ratings
const ratingSum = movies.map(movie => movie.imdbRating).reduce((acc, value) =\
> acc + value, 0);
// ...
Higher-order functions
Throughout this chapter, we have leveraged the fact that JavaScript functions can be passed
around just like any other value. We say that functions are first-class citizens in JavaScript,
which means that they are treated equal to other types.
Thanks to their first-class citizenry, functions can be combined together, rendering programs
even more expressive and enabling a truly functional programming style. A function that takes
another function as a parameter or returns another function is called an higher-order function.
Check out this final version of our example program.
console.log(titles(movieList));
const nolanMovieList = filter(movieList, byNolan);
console.log(nolanMovieList.length);
console.log(titles(filter(movieList, goodRating)));
console.log(average(ratings(nolanMovieList)));
We have defined helper functions that we combine to achieve the desired behaviour. The code is
concise and self-describing. Since it takes the filtering function as a parameter, our own filter()
function is an example of an higher-order function.
Coding time!
Older movies
Improve the example movie program from above so that it shows the titles of movies released
before year 2000, using functional programming.
const movieList = [{
title: "Batman",
year: 1989,
director: "Tim Burton",
imdbRating: 7.6
}, {
title: "Batman Returns",
year: 1992,
director: "Tim Burton",
imdbRating: 7.0
}, {
title: "Batman Forever",
year: 1995,
director: "Joel Schumacher",
imdbRating: 5.4
}, {
title: "Batman & Robin",
year: 1997,
director: "Joel Schumacher",
imdbRating: 3.7
}, {
title: "Batman Begins",
year: 2005,
director: "Christopher Nolan",
imdbRating: 8.3
}, {
title: "The Dark Knight",
year: 2008,
director: "Christopher Nolan",
imdbRating: 9.0
}, {
title: "The Dark Knight Rises",
year: 2012,
director: "Christopher Nolan",
imdbRating: 8.5
}];
console.log ( moviesBefore2000 );
Execution result
Government forms
Complete the following program to compute and show the names of political forms ending with
"cy".
const governmentForms = [{
name: "Plutocracy",
definition: "Rule by the weathly"
},{
name: "Oligarchy",
definition: "Rule by a small number of people"
},{
name: "Kleptocracy",
definition: "Rule by the thieves"
},{
name: "Theocracy",
definition: "Rule by a religious elite"
}, {
name: "Democracy",
definition: "Rule by the people"
}, {
name: "Autocracy",
definition: "Rule by a single person"
}];
Arrays sum
Complete the following program to compute and show the total sum of the values in each of the
arrays.
Discover functional programming 97
const arrays = [
[1, 4],
[11],
[3, 5, 7]
];
Student results
Here’s a program that shows female students results (name and average grade). Refactor it using
functional programming. Execution result must stay the same.
const students = [{
name: "Anna",
sex: "f",
grades: [4.5, 3.5, 4]
}, {
name: "Dennis",
sex: "m",
country: "Germany",
grades: [5, 1.5, 4]
}, {
name: "Martha",
sex: "f",
grades: [5, 4, 2.5, 3]
}, {
name: "Brock",
sex: "m",
grades: [4, 3, 2]
}];
});
}
}
console.log(femaleStudentsResults);
Execution result
11. Project: a social news program
Now that you’ve discovered the basics of programming, let’s go ahead and build a real project.
Objective
The goal of this project is to build a basic social news program. Its user will be able to show a
list of links and add new ones.
Functional requirements
• A link is defined by its title, its URL and its author (submitter).
• At launch, the program displays a start menu with the possible actions in an alert window
and asks the user for his choice. Possible actions are:
– Show the list of links.
– Add a new link.
– Remove an existing link.
– Quit the program.
• Showing the list of links displays the index (rank) and the properties of each link in an
alert window, or a message in the absence of any link.
• When adding a link, the program asks the user for the new link properties (title, URL and
author). The link is then created. Subsequently, it must appear in the showed links.
• If the new link URL does not start with "http://" or "https://", the program adds
"http://" at its beginning.
• When removing a link, the user is asked for the link index until it is correct. The associated
link is then removed. Subsequently, it must disappear from the showed links. Removing a
link is not possible if there are no existing links.
• After an action is performed, the start menu is shown again. This goes on until the user
chooses to quit the program.
Technical requirements
• All your code should be correctly indented.
• Names should be wisely chosen and adhere to the camelCase convention.
• Code duplication should be avoided.
Project: a social news program 100
Expected result
Here are a few screenshots of the expected result.
Start menu
Showing a link
Project: a social news program 101
TL;DR
• The World Wide Web¹ (or Web) is an information space built on top of the Internet². Web
resources are accessible via their URL³, and can contain hyperlinks⁴ to other resources.
• A web page is a document suitable for the Web. Creating web pages usually involves
three technologies: HTML⁵ to structure the content, CSS⁶ to define its presentation and
JavaScript to add interactivity.
• An HTML document is made of text and structural elements called tags that describe the
page content: paragraphs, headings, hyperlinks, images, etc.
• CSS uses selectors to declare which HTML elements a style applies to. Elements can be
selected by tag name (h1), by class (.done) or by identifier (#rude).
• An HTML document can include a CSS stylesheet with a <link> tag and a JavaScript file
with a <script> tag.
<!doctype html>
<html>
<head>
<!-- Info about the page: title, character set, etc -->
<body>
<!-- Page content -->
</html>
¹https://en.wikipedia.org/wiki/World_Wide_Web
²https://en.wikipedia.org/wiki/Internet
³https://en.wikipedia.org/wiki/Uniform_Resource_Locator
⁴https://en.wikipedia.org/wiki/Hyperlink
⁵https://en.wikipedia.org/wiki/HTML
⁶https://en.wikipedia.org/wiki/Cascading_Style_Sheets
What’s a web page? 104
• A browser is the software you use to visit webpages and use web applications. The modern
ones include a set of developer tools to ease the task of developing for the web.
HTML
HTML, short for HyperText Markup Language¹², is the document format of web pages. An HTML
document is made of text and structural elements called tags. Tags are used to describe the page
content: paragraphs, headings, hyperlinks, images, etc.
Here is an example of a simple web page, usually stored as an .html file.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>My web page</title>
</head>
<body>
<h1>My web page</h1>
<p>Hello! My name's Baptiste.</p>
<p>I live in the great city of <a href="https://en.wikipedia.org/wiki/Bor\
deaux">Bordeaux</a>.</p>
</body>
</html>
⁷https://en.wikipedia.org/wiki/World_Wide_Web
⁸https://en.wikipedia.org/wiki/Internet
⁹https://en.wikipedia.org/wiki/Uniform_Resource_Locator
¹⁰https://en.wikipedia.org/wiki/Hyperlink
¹¹https://en.wikipedia.org/wiki/Web_browser
¹²https://en.wikipedia.org/wiki/HTML
What’s a web page? 105
Display result
CSS
CSS, or Cascading Style Sheets¹⁵, is a language used to alter the presentation of web pages.
CSS uses selectors to declare which HTML elements a style applies to. Many selecting strategies
are possible, most notably:
Here is an example of a simple CSS style sheet, usually stored as a .css file.
A style sheet is associated with an HTML document using a link tag in the head part of the page.
JavaScript
JavaScript can interact with an HTML document to provide dynamic interactivity: responses to
user actions on the page, dynamic styling, animations, etc. It is the only programming language
understood by all web browsers.
A JavaScript file, usually stored in a .js file, is loaded by a web page with a <script> tag.
Check out the following links to discover more about browser developer tools:
Even if you’re using CodePen to follow along this book, you can still use the
developer tools in addition to the CodePen console. For performance reasons, the
CodePen console does not always show the same amount of information as the
“real” browser console.
Coding time!
You can skip this exercise if you ahve prior experience with HTML and CSS.
²³https://www.khanacademy.org/computing/computer-programming/html-css/web-development-tools/a/using-the-browser-developer-
tools
²⁴https://openclassrooms.com/courses/optimize-your-website-with-devtools
²⁵https://developer.chrome.com/devtools
²⁶https://developer.mozilla.org/son/docs/Tools
What’s a web page? 108
Expected result
13. Discover the DOM
This chapter will help you discover how a web page is shown by a browser.
TL;DR
• A web page is a structured document containing both text and HTML tags. The DOM, or
Document Object Model, is a standardized way to define a web page’s structure.
• Tho DOM is alos an API allowing programmatical interactions with the web page. With
JavaScript, you can access the structure of a page displayed in a browser and modify it.
• The DOM represents a web page as a hierarchy of objects, where each object corresponds
to a node in the nested HTML element tree.
• The document variable provides access to the root of the DOM tree and corresponds to the
<html> element in the HTML itself.
• DOM objects have properties and methods that you can manipulate with JavaScript. For
example, nodeType returns the node type, childNodes contains a collection of child nodes,
and parentNode returns the parent node.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>My web page</title>
</head>
<body>
<h1>My web page</h1>
<p>Hello! My name's Baptiste.</p>
<p>I live in the great city of <a href="https://en.wikipedia.org/wiki/Bor\
deaux">Bordeaux</a>.</p>
</body>
</html>
Discover the DOM 111
Display result
To create this result, the browser first takes the HTML code and builds a representation of its
structure. It then displays this structure in the browser.
The browser also offers a programmatical access to its structured representation of a displayed
web page. Using this interface, you can dynamically update the page: adding or removing
elements, changing styles, etc. This is how you create interactive web pages.
The structured representation of a web page is called DOM, short for Document Object Model.
The DOM defines the structure of a page and a way to interact with it. This means it’s a
programming interface, or API (Application Programming Interface). JavaScript is the language
of choice for interacting with the DOM.
At the dawn of the Web, each browser was using its own DOM, giving headaches to
JavaScript developers trying to code web pages. These hard times are over: through
a World Wide Web Consortium¹ (W3C) effort, the first version of a unified DOM
was created in 1998. Nowadays, all recent browsers use a standardized DOM.
Example structure
Each entity in the tree is called a node. There are two types of nodes:
• Those (in blue here) that correspond to HTML tags like <body> or <p>. These nodes are
called element nodes and they can have subnodes, called child nodes or children.
• Those (in red) that match the textual content of the page. These nodes are called text nodes
and do not have children.
Execution result
As expected, the DOM object body is an element node because it’s an HTML tag.
The childNodes property of an element node is not a real JavaScript array, but rather
a NodeList² object. Not all of the standard array methods are applicable to it.
The following code would display the first child of the body node.
²https://developer.mozilla.org/en-US/docs/Web/API/NodeList
Discover the DOM 114
Execution result
Wait… Why isn’t the first child node h1, since that’s the first element in the body’s
HTML?
That’s because spaces between tags and line returns in HTML code are considered text nodes by
the browser. The node h1 is therefore the second child node of the body. Let’s double check that:
Execution result
To eliminate these text nodes between tags, you could have written the HTML page in a more
condensed way.
It’s better, however, to take the text nodes between tags into accouant than to sacrifice lisibility
and code indentation.
Discover the DOM 115
Execution result
Again, spaces and line returns count as text nodes in the DOM.
For the DOM root node (document), the value of parentNode is null since it has no
parent node.
const h1 = document.body.childNodes[1];
console.log(h1.parentNode); // Show the body node
console.log(document.parentNode); // Will show null, since body has no parent\
node
Execution result
There are other properties that we will not discuss here that let you navigate through
the DOM, like firstChild, lastChild or nextSibling.
Coding time!
<h1>A title</h1>
<div>Some text with <a href="#">a link</a>.</div>
TL;DR
• Rather than go through the DOM node by node, you can quickly access one or more
elements using selection methods.
• The getElementsByTagName(), getElementsByClassName() and getElementById() meth-
ods respectively search items by tag name, class, and ID. The first two methods return a
list, and the latter returns a single item.
• The querySelectorAll() and querySelector() methods make it possible to search for
items using a CSS selector. The first method returns all matching items, and the second
returns only the first.
• The innerHTML property returns the HTML content of an element. The textContent
property returns its textual content without any HTML markup.
• The getAttribute() and hasAttribute() methods allow access to element attributes.
The classList property and its method contains() provides access to an element’s
classes.
Selecting elements
Execution result
This technique is pretty awkward and error-prone. The code is difficult to read and must be
updated if new elements are further inserted in the web page. Fortunately, there are much better
solutions.
Traverse the DOM 120
Execution result
Suffixing JavaScript variables associated to DOM element nodes with Element (or
Elements when the variable contains several nodes) is a popular naming convention.
We’ll stick to it throughout this book.
¹https://developer.mozilla.org/en-US/docs/Web/API/NodeList
Traverse the DOM 121
Execution result
Execution result
Beware: contrary to others, the getElementById() method does not contain any 's'
after the "Element" word.
This syntax is a little clunky though. Let’s learn two new methods that make finding elements
easier.
The first is querySelectorAll(), with which you can use CSS selectors to identify elements.
Traverse the DOM 123
// All paragraphs
console.log(document.querySelectorAll("p").length); // 3
Check the Mozille Developer Network² for a primer on the different CSS selectors
available.
The second method using CSS selectors is called querySelector(). It works the same way as
querySelectorAll() but only returns the first matching element. It returns null if no associated
element can be found.
Execution result
²https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors
³https://jsperf.com/getelementsbyclassname-vs-queryselectorall/195
Traverse the DOM 124
HTML content
The innerHTML property will retrieve the HTML contents of your DOM element.
Execution result
This property has been introduced by Microsoft and is not part of the W3C DOM
specification, but it is nonetheless supported by all major browsers.
Textual content
The textContent property returns all the text content of a DOM element, without any HTML
markup.
Traverse the DOM 126
Execution result
Attributes
The getAttribute() method can be applied to a DOM element and will return the value of a
given attribute.
Traverse the DOM 127
Execution result
Some attributes are directly accessible as properties. This is true for the id, href, and value
attributes.
Execution result
You can check for the existence of an attribute using the hasAttribute() method as seen in the
example below.
if (document.querySelector("a").hasAttribute("target")) {
console.log("The first link has a target attribute.");
} else {
console.log("The first link does not have a target attribute."); // Will \
be shown
}
Classes
In a web page, a tag can have multiple classes. The classList property retrieves a DOM element’s
list of classes.
Traverse the DOM 128
You also have the opportunity to test the presence of a class on an element by calling the
contains() on the class list, passing the class to test as a parameter.
if (document.getElementById("ancient").classList.contains("wonders")) {
console.log("The element with ID 'ancient' has the class 'wonders'."); //\
Will be shown
} else {
console.log("The element with ID 'ancient' does not have the class 'wonde\
rs'.");
}
This is only a part of the DOM traversal API. For more details, check the Mozilla
Developer Network⁴.
Coding time!
Counting elements
Here is some HTML code (content is by French poet Paul Verlaine).
Complete the following program to write the countElements() function, that takes a CSS selector
as a parameter and returns the number of corresponding elements.
⁴https://developer.mozilla.org/en-US/docs/Web/API/Element
Traverse the DOM 129
Handling attributes
Here is the description of several musical instruments.
Expected result
Traverse the DOM 130
Add the following new instrument at the end of the HTML list, then check your program’s new
result.
<li id="harpsichord">
The <a href="https://en.wikipedia.org/wiki/Harpsichord">harpsichord</a>
</li>
Expected result
Handling classes
Improve the previous program to add a has() function that test if an element designated by its
ID has a class. The function shows true, false or an error message if the element can’t be found.
Expected result
15. Modify the page
Let’s see how to use JavaScript to modify a web page once it’s been loaded by the browser! You
can thus make your content more dynamic and interactive.
TL;DR
• The innerHTML, textContent and classList properties, as well as the setAttribute
method, let you modify a DOM element’s information.
• You create new DOM nodes via methods createTextNode() (for, well, text nodes) and
createElement() (for elements themselves).
• The appendChild() method lets you insert a new node as the last child of a DOM element.
• The insertBefore() and insertAdjacentHTML() methods are alternative possibilities for
adding content.
• You can replace existing nodes with the replaceChild() method or remove them with
removeChild().
• The JavaScript style property represents the style attribute of a DOM node. It lets you
modify the element’s style by defining values of its CSS properties.
• CSS properties that involve multiple words are written in camelCase when dealing with
JavaScript. For example, font-family becomes fontFamily.
• The style property isn’t enough to access an element’s style. You should use the
getComputedStyle() function instead.
• Manipulating the DOM with JavaScript should be done sparingly so that page performance
doesn’t suffer.
Example page
The examples in the next paragraphs use the HTML code below.
Modify the page 133
HTML content
The innerHTML property can be used to change the content of an element within the DOM.
For example, you can add a new language to our list with the code below. We’ll access the <ul>
tag identified by "languages" and then add an entry to the end of the list via an operator (+=)
and an <li>.
Execution result
The innerHTML property is often used to “empty” content. Try the following example:
Before moving on, remove the above line from your JavaScript program. Otherwise,
you’ll have no content!
When using innerHTML, you put some HTML content into strings. To keep your code
readable and avoid mistakes, you should only use innerHTML to make small content
changes. You’ll discover more versatile solutions below.
Modify the page 134
Text content
Use the textContent property to modify the text content of a DOM element. Here is how to
complete the title displayed by our page.
Execution result
Attributes
The setAttribute() method sets the value of an attribute of an element. You pass the name and
value of the attribute as parameters.
As you saw in the previous chapter, some attributes exist as properties and can be directly
updated.
Classes
You can use the classList property to add or remove classes from a DOM element!
Modify the page 135
Execution result
For example, suppose you want to add the language “Python” to the list of languages on our
page. Here’s the JavaScript code you’d use to do so.
Execution result
// ...
pythonElement.id = "python"; // Define element ID
pythonElement.textContent = "Python"; // Define its text content
// ...
document.getElementById("languages").appendChild(pythonElement); // Insert th\
e new element into the DOM
Execution result
Execution result
The following example uses insertAdjacentHTML() to add JavaScript at the top of the language
list.
Modify the page 139
Execution result
Replacing a node
A DOM element can be replaced with the replaceChild() method. This replaces a child node
of the current element with another node. The new node and node-to-be-replaced are passed as
parameters (in that order).
The example shows replacing the Perl language with Lisp instead.
Execution result
Removing a node
Lastly, you can delete a node thanks to a method called removeChild(), to which you’ll pass the
node-to-be-removed as a parameter.
Execution result
Modify the page 141
Styling elements
JavaScript not only lets you interact with your web page structure, but it also lets you change
the style of elements. It’s time to learn how.
Here is the example HTML content used in the next paragraphs.
<p>First</p>
<p style="color: green;">Second</p>
<p id="para">Third</p>
And here is the associated CSS stylesheet. The rules in a stylesheet determine the appearance
of elements on a page. Here, the one element we’re adjusting via CSS here is the element with
the para ID. Its text will be blue and in italics.
#para {
font-style: italic;
color: blue;
}
Display result
Some CSS properties have compound names, meaning they’re composed of two words (like
background-color). To interact with these properties via JavaScript, you have to ditch the
hyphen and capitalize the first letter of following words.
This example modifies the same paragraph element’s font-family and background-color
properties.
Modify the page 142
// ...
paragraphElement.style.fontFamily = "Arial";
paragraphElement.style.backgroundColor = "black";
Execution result
Execution result
Because the style property used in this code only represents the style attribute of the element.
Using this property, you cannot access style declarations defined elsewhere, for example in a CSS
stylesheet. This explains why the third paragraph’s style, defined externally, is not shown here.
Execution result
The blue color is represented as 3 color values: red, green, and blue (RGB). For each
of these primary colors, values will always be between or equal to 0 and 255.
Coding time!
Adding a paragraph
Improve the languages example to add a paragraph (<p> tag) containing a link (<a> tag) to the
URL https://en.wikipedia.org/wiki/List_of_programming_languages.
Execution result
Newspaper list
Here is the HTML code of a web page.
Modify the page 145
<h3>Some newspapers</h3>
<div id="content"></div>
Write a program that show on this page a list of newspapers defined in a JavaScript array. Each
link must be clickable.
// Newspaper list
const newspapers = ["https://www.nytimes.com", "https://www.washingtonpost.co\
m", "http://www.economist.com"];
Execution result
Mini-dictionary
Here is the HTML code of a web page.
<h3>A mini-dictionary</h3>
<div id="content"></div>
Write a program that show on this page a list of terms and definitions defined in a JavaScript
array.
const words = [{
term: "Procrastination",
definition: "Avoidance of doing a task that needs to be accomplished"
}, {
term: "Tautology",
definition: "logical argument constructed in such a way that it is logicall\
y irrefutable"
}, {
term: "Oxymoron",
definition: "figure of speech that juxtaposes elements that appear to be co\
ntradictory"
}];
Modify the page 146
Use the HTML <dl> tag to create the list (more on this tag³). Each term of the dictionary should
be given more importance with a <strong> tag.
Execution result
Updating colors
The following HTML content defines three paragraphs.
<h1>Paragraph 1</h1>
<div>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec dignissim\
fringilla dapibus. Curabitur placerat efficitur molestie. Quisque quis conse\
quat nibh. Aenean feugiat, eros eget aliquam vulputate, leo augue luctus lect\
us, non lobortis libero quam non sem. Aliquam sit amet tincidunt ex, mollis i\
nterdum massa.</div>
<h1>Paragraph 2</h1>
<div>Vivamus at justo blandit, ornare leo id, vehicula urna. Fusce sed felis \
eget magna viverra feugiat eget nec orci. Duis non massa nibh. Aenean vehicul\
a velit a magna lobortis tempor ut quis felis. Proin vitae dui a eros facilis\
is fringilla ut ut ante.</div>
<h1>Paragraph 3</h1>
<div>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis sit amet p\
haretra massa. Nulla blandit erat nulla, et scelerisque libero varius ut. Pra\
esent bibendum eu magna ullamcorper venenatis. Sed ut pellentesque leo. Sed u\
ltrices sapien consequat odio posuere gravida.</div>
Write a program that asks the user for the new text color, then for the new background color.
The page is then updated accordingly.
³https://developer.mozilla.org/en-US/docs/Web/HTML/Element/dl
Modify the page 147
<div id="content">ABC
<br>Easy as
<br>One, two, three
</div>
<div id="infos"></div>
#content {
float: right;
margin-top: 100px;
margin-right: 50px;
}
Write a program that adds to the page a list showing the height and witdh of the element
identified by “content”.
Modify the page 148
Execution result
16. React to events
To make a web page interactive, you have to respond to user actions. Let’s discover how to do
so.
TL;DR
• You can make a web page interactive by writing JavaScript code tied to events within the
browser.
• Numerous types of events can be handled. Each event type is associated with an Event
object that contains properties giving information about the event.
• keypress, keydown and keyup events let you react to keyboard-related events.
• click, mousedown and mouseup events let you react to mouse-related events.
• Page loading and closing are associated with the events load and beforeunload respec-
tively.
• An event propagates within the DOM tree from its node of origin until the document root.
This propagation can be interrupted with the stopPropagation() method.
• Calling the preventDefault() method on an Event object cancels the default behavior
associated to the action that triggered the event.
Introduction to events
Up until now, your JavaScript code was executed right from the start. The execution order of
statements was determined in advance and the only user interactions were data input through
prompt() calls.
To add more interactivity, the page should react to the user’s actions: clicking on a button, filling a
form, etc. In that case, the execution order of statements is not determined in advance anymore,
but depends on the user behavior. His actions trigger events that can be handled by writing
JavaScript code.
This way of writing programs is called event-driven programming. It is often used by user
interfaces, and more generaly anytime a program needs to interact with an user.
A first example
Here’s some starter HTML code.
function showMessage() {
alert("Hello!");
}
// Access the button
const buttonElement = document.getElementById("myButton");
// Listen to the "click" event
buttonElement.addEventListener("click", showMessage);
Execution result
Category Examples
Keyboard events Pressing or releasing a key
Mouse events Clicking on a mouse button, pressing or releasing a mouse
button, hovering over a zone
Window events Loading or closing a page, resizing, scrolling
Form events Changing focus on a form field, submitting a form
Every event is associated to an Event object which has both properties (informations about the
event) and methods (ways to act on the event). This object can be used by the handler function.
Many properties of the Event object associated to an event depend on the event type. Some
properties are always present, like type that returns the event type and target that return the
event target (the DOM element that is the event source).
The Event object is passed as a parameter to the handler function. The following code uses it to
show the event type and target in the console.
// Show event type and target when the user clicks on the button
document.getElementById("myButton").addEventListener("click", e => {
console.log(`Event type: ${e.type}, target: ${e.target}`);
});
The parameter name chosen for the Event object is generaly e or event.
Execution result
Key presses
The most common solution for reacting to key presses on a keyboard involves handling keypress
events that happen on a web page (the DOM body element, which corresponds to the global
variable called document in JavaScript).
React to events 152
The following example shows in the console the character assoaciated to a pressed key. Yhe
character info is given by the charCode property of the Event object associated to the event.
This property returns a numerical value (called Unicode value) that can be translated to a string
value by the String.FromCharCode() method.
Execution result
To manage the press and release of any key (not only the ones producing characters), you’ll use
the keydown and keyup events. This example uses the same function to manage two events. This
time, the key’s code is accessible in the keyCode property of the Event object.
Execution result
This results demonstrates that the launch order of keyboard-related events is as follows: keydown
-> keypress -> keyup.
Mouse clicks
Mouse clicks on any DOM element produce a event of the click type. Tactile interfaces like
smartphones and tablets also have click events associated with buttons, which are kicked off
by actually pressing a finger on the button.
The Event object associated with a click event has a button property which lets you know
the mouse button used, as well as clientX and clientY properties that return the horizontal
and vertical coordinates of the place where the click happened. These coordinates are defined
relative to the page zone currently shown by the browser.
React to events 154
The below code shows information on all click events that happen on a web page. The
mouseInfo() function associated to the event uses another function, called getMouseButton(),
to retrieve the clicked mouse button.
Execution result
You can use mousedown and mouseup events similarly to keydown and keyup to deal with mouse
buttons’ press and release events. The code below associates the same handler to these two events.
Execution result
The appearance order for mouse-related events is: mousedown -> mouseup -> click.
React to events 156
Page loading
Depending on how complex it is, a web page can take time to be entirely loaded by the browser.
You can add an event listener on the load event produced by the window object (which represent
the brower window) to know when this happens. This avoids messy situations where JavaScript
interacts with pages that aren’t fully loaded.
The following code displays a message in the console once the page is fully loaded.
Page closing
You sometimes want to react to page closing. Closing happens when the user closes the tab
displaying the page or navigates to another page in this tab. A frequent use case consists of
showing a confirmation dialog to the user. Handling page closing is done by adding a handler
for the beforeunload event on the window object.
Setting the value of the returnValue property on the Event object is the standard
way of triggering a confirmation dialog showing this value. However, some browsers
use the return value of the event listener instead. The previous code associate the
two techniques to be universal.
Event propagation
The DOM represents a web page as a hierarchy of nodes. Events triggered on a child node are
going to get triggered on the parent node, then the parent node of the parent node, up until the
root of the DOM (the document variable). This is called event propagation.
To see propagation in action, use this HTML code to create a small DOM hierachy.
React to events 157
Here’s the complementary JavaScript code. It adds click event handlers on the button, its parent
(the paragraph), and the parent of that too (the root of the DOM).
Execution result
The result in the browser console demonstrates the propagation of click events from the button
up to the document level. You clicked the button, which means you also clicked the paragraph,
which means you also clicked the document.
But maybe you only want an event to kick off once the button is clicked and not count
its larger ecosystem? Event propagation can be interrupted at any moment by calling the
stopPropagation() method on the Event object from an event handler. This is useful to avoid
the same event being handled multiple times.
Adding a line in the button’s click handler prevents the click event from propagating every-
where in the DOM tree.
React to events 158
Execution result
Now clicking on the links shows a dialog instead of navigating to its target.
Execution result
React to events 159
Coding time!
Counting clicks
Start with the following HTML content.
Write the JavaScript code that counts the number of clicks on the myButton button by updating
the clickCount element. The desactivate button stop the counting.
Changing colors
Here is some HTML content to start with.
<h1>Paragraph 1</h1>
<div>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec dignissim\
fringilla dapibus. Curabitur placerat efficitur molestie. Quisque quis conse\
quat nibh. Aenean feugiat, eros eget aliquam vulputate, leo augue luctus lect\
us, non lobortis libero quam non sem. Aliquam sit amet tincidunt ex, mollis i\
nterdum massa.</div>
<h1>Paragraph 2</h1>
<div>Vivamus at justo blandit, ornare leo id, vehicula urna. Fusce sed felis \
eget magna viverra feugiat eget nec orci. Duis non massa nibh. Aenean vehicul\
a velit a magna lobortis tempor ut quis felis. Proin vitae dui a eros facilis\
is fringilla ut ut ante.</div>
<h1>Paragraph 3</h1>
<div>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis sit amet p\
haretra massa. Nulla blandit erat nulla, et scelerisque libero varius ut. Pra\
esent bibendum eu magna ullamcorper venenatis. Sed ut pellentesque leo. Sed u\
ltrices sapien consequat odio posuere gravida.</div>
Write the associated JavaScript code that update background color of all div tags according to
the key (R, Y, G or B) pressed by the user.
React to events 160
Execution result
A dessert list
The following HTML code defines a list of desserts, empty for now.
<ul id="desserts">
</ul>
Write the JavaScript code that adds a new dessert to the list when the user clicks on the button.
The dessert name is chosen by the user.
Bonus points for adding the possibility of changing a dessert’s name when clicking on it.
React to events 161
Execution result
Interactive quiz
Here is the starter HTML code.
<div id="content"></div>
Complete this code to display the questions in the <div> element of the page, with a "Show the
answer" button next to each question. Clicking this button replaces it with the answer for this
question.
React to events 162
Execution result
Conclusion
Acknowledgments
This book was built upon two online courses I wrote for the French EdTech startup OpenClass-
rooms¹:
Thanks to Jessica Mautref⁶ for her watchful eye during the writing process, and to Emily Reese⁷
for the initial English translation. Both also contributed many good ideas.
I’ve been inspired by other authors who decided to publish their books in an open way: Kyle
Simpson⁸, Nicholas C. Zakas⁹, Axel Rauschmayer¹⁰ and Marijn Haverbeke¹¹.
Thanks to everyone who improved the book content through contributions: Gilad Penn,
NewMountain, Emre Akbudak, opheron. Special thanks to Theo Armour.
Cover logo: Creative blue swirl¹² by Free Logo Design¹³.
¹https://openclassrooms.com
²https://openclassrooms.com/courses/learn-the-basics-of-javascript
³https://openclassrooms.com/courses/apprenez-a-coder-avec-javascript
⁴https://openclassrooms.com/courses/use-javascript-on-the-web
⁵https://openclassrooms.com/courses/creez-des-pages-web-interactives-avec-javascript
⁶https://www.linkedin.com/in/jessicamautref
⁷https://www.linkedin.com/in/eclairereese
⁸https://github.com/getify
⁹https://www.nczonline.net/
¹⁰http://dr-axel.de/
¹¹http://marijnhaverbeke.nl/
¹²http://www.logoopenstock.com/logo/preview/64186/creative-blue-swirl-logo-design
¹³http://www.free-logodesign.com/