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
Following along . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ii
Welcome to programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . iv
TL;DR . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . iv
Whats a program? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . iv
How do you create programs? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . v
Learn to code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . vii
Introducing JavaScript . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ix
TL;DR . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ix
History of JavaScript . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ix
JavaScript: an essential language . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xi
Version used in this book . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xi
3. Add conditions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
TL;DR . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
Whats 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
Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 255
Acknowledgments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 259
Appendices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 260
Environment setup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 261
Prerequisite: a modern browser . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 261
Solution A: coding online . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 261
Solution B: building a local development environment . . . . . . . . . . . . . . . . . 263
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 web application development on both the client and server sides. Each part
depends on the previous ones, but theres no other prerequisite to reading.
Each chapter starts with a TL;DR paragraph which summarizes it, so youll be able to skip ahead
if you already know a chapters content.
At the end of each chapter, a series of short and focused exercises will make you put your newly
acquired skills into practice. Each part ends with a project guiding you in the creation of a social
news web application.
Following along
You have two options for following along, depending on how eager you are to get into the action
and how comfortable you feel setting up your local machine:
Coding online, using feature-packed JavaScript playgrounds like CodePen1 and Glitch2 .
1
https://codepen.io
2
https://glitch.com
About this book iii
First option is the easiest and quickest; second one is more powerful and will probably become
necessary as you tackle bigger programming challenges in a not-so-distant future. Refer to the
appendix for details on both.
Whichever solution you may choose, be sure to test every code sample and search every exercise
and project. Reading along is not enough: coding along is mandatory to get a real grasp of how
things work and become a capable programmer.
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 programs source code.
The programmers 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.
Whats 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.
Lets 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 simply do what theyre
told to do! Their value comes from how they can quickly handle and process huge amounts of
information.
Welcome to programming v
A computer often requires human intervention. Thats 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. Its 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, isnt it? Fortunately, other programming languages are much simpler and conve-
nient to use than assembly language.
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 throughout 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 languages 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 vii
Learn to code
Introduction to algorithms
Except in very simple cases, you dont create programs by writing source code directly. Youll
first need to think about the instructions youll 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 viii
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 Eich3 , who at the time worked for Netscape4 , which created the first popular web
browser (Firefoxs ancestor).
A browser is the software you use to visit webpages and use web applications.
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.
3
https://en.wikipedia.org/wiki/Brendan_Eich
4
https://en.wikipedia.org/wiki/Netscape_Communications
Introducing JavaScript x
Web builders started 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 its now a very fast language.
This led to the emergence of the Node.js5 platform, which allows you to create JavaScript
applications outside the browser. Thanks to a software called MongoDB6 , 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 thats compatible with these systems. These tools are
almost always based on JavaScript!
5
https://nodejs.org
6
https://www.mongodb.com
Introducing JavaScript xi
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
table9 ).
7
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
8
https://en.wikipedia.org/wiki/ECMAScript
9
http://kangax.github.io/compat-table/es6/
I Learn to code programs
1. 3, 2, 1 Code!
Lets get started! This chapter will introduce you to the fundamentals of programming including
values, types, and program structure.
TL;DR
The JavaScript command console.log() shows a message in the console, an information
zone available in most JavaScript environments.
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 + operator 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.
This program displays the text "Hello from JavaScript!" in the console, a zone displaying
textual information available in most JavaScript environments, such as browsers.
To achieve this, it uses a JavaScript command named console.log(), which role is to display a
piece of information. The text to be displayed is placed between parentheses and followed by a
semicolon, which marks the end of the line.
Displaying a text on the screen (the famous Hello World1 all programmers know) is often the first
thing youll do when you learn a new programming language. Its the classic example. Youve
already taken that first step!
1
https://en.wikipedia.org/wiki/Hello_world
3, 2, 1 Code! 3
Number
A number is a numerical value (thanks Captain Obvious). Lets 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 youll see are summarized in the
following table. All of them produce a number result.
Operator Role
+ Addition
- Subtraction
* 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 dont
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 subtract string values like youd 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 whats called the source code of the program.
3, 2, 1 Code! 4
The lines of text in a source code file are called lines of code.
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 its 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. Its the
combination of these individual results that produces the final result of the program.
Heres an example of a JavaScript program including several statements.
Execution result
3, 2, 1 Code! 5
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 werent
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 programs purpose or structure. Adding comments
to complicated or critical parts is a good habit you should build right now!
3, 2, 1 Code! 6
Coding time!
Lets put your brand new coding skills into practice.
Presentation
Write a program that displays your name and age. Heres the result for mine.
Minimalistic calculator
Write a program that displays the results of adding, subtracting, multiplying 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 will never change), its 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 implicitly during the evaluation of an expression, or
explicitly when using the Number() and String() commands, to obtain 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 visibility. Following a naming convention like
camelCase1 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!
1
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 sign ($) 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 dont 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. Thats
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.
Heres 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 didnt 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! Youll
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, youre 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 contains 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
expressions 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 delimit 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 expressions evaluation can result in type conversions. These are called implicit conversions,
as they happen automatically without the programmers 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 youll 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, a 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. Youll 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 returns 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, lets discuss variable naming. The computer doesnt 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:
const a = 5.5;
const b = 3.14;
const c = 2 * a * b;
console.log(c);
They function in the same way, but the second version is much easier to understand.
Naming things is an important part of the programmers job. Refer to the appendix for some
useful advice.
Play with variables 14
Coding time!
Build a habit of choosing good variable names in all exercises, starting with these ones.
Improved hello
Write a program that asks the user for his first name and his last name. The program then displays
them in one sentence.
Final values
Observe the following program and try to predict the final values of its variables.
let a = 2;
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, it 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.
Play with variables 15
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. Lets 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 visibility, its statements are generally indented (shifted to the right).
The comparison operators ===, !==, <, <=, > and >= 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. There 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) and
! (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
}
Whats a condition?
Suppose we want to write a program that asks the user to enter a number and then displays a
message if the number is positive. Here is the corresponding algorithm.
Enter a number
If the number is positive
Display a message
The message should display only if the number is positive; this means its subject to a
condition.
The if statement
Heres 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: its 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 its safer to use === and !== (more details1 ).
1
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness
Add conditions 19
Its easy to confuse comparison operators like === (or ==) with the assignment operator
=. Theyre very, very different. Be warned!
Now lets 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
Youll often want to have your code execute one way when somethings true and another way
when somethings 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
Lets go to the 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.
Lets 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 its not, we know for sure that its 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 programs flow. There is
no limit to the possible depth of condition nesting, but too many will affect program visibility.
A particular case happens when the only statement in an else block is an if. In that case, you
can write this else on the same line as the if and without braces. Heres a more concise way to
write our example program.
And operator
Suppose you want to check if a number is between 0 and 100. Youre essentially checking if its
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 <= number <= 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 avoid 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.
Heres its truth table:
Not operator
Theres another operator for when you know what you dont want: the not operator! Youll use
a ! for this.
Add conditions 23
console.log(!true); // false
console.log(!false); // true
Multiple choices
Lets 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 pieces of 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. Its 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 compares their values and displays an
appropriate 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 depending 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 information (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, well 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 with 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 with 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
youve 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 its told to stop. Each
time the code runs, its called an iteration.
Example
Heres a sample program written with a while loop.
let number = 1;
while (number <= 5) {
console.log(number);
number++;
}
Repeat statements 29
Just like the previous one, this code block shows all integer numbers between 1 and 5.
Execution result
How it works
Youll 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 its
true or not. The code associated with a loop is called its body.
If the conditions value is true, the code in the while loops body runs. Afterwards, the
condition is re-evaluated to see if its still true or not. The cycle continues!
If the conditions value is false, the code in the loop stops running or doesnt run.
The loop body must be placed within curly braces, except if its only one statement.
For now, always use curly braces for your loops.
Example
Heres the same program as above written instead with a for loop.
let number;
for (number = 1; number <= 5; number++) {
console.log(number);
}
How it works
Heres the for loop syntax.
Initialization only happens once, when the code first kicks off. Its 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 its true, the code runs.
If not, the code doesnt run.
The final expression is evaluated after the loop runs each time. Its often used to update
the value of the variable associated with 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 never 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 youre using a for loop, youll 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 cant know how many times itll 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!
Try 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 its done, improve it so that the number of turns is given by the user.
Parity
Check the following program that shows even numbers (divisible by 2) between 1 and 10.
This program uses the modulo operator %, which calculates the remainder after division of one
number by another. Its often used to assess number parity.
Improve the program so that it also shows odd numbers. Improve it again to replace the initial
number 1 by a number given by the user.
This program must show exactly 10 numbers including the first one, not 11 numbers!
Repeat statements 33
Input validation
Write a program that continues to ask the user for a number until the entered number is less
than or equal to 100.
When you are done with the above, improve the program so that the terminating 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 you are done, improve the program so it only accepts 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 its done, improve it so that the program shows "FizzBuzz" instead for numbers divisible
both by 3 and by 5.
This exercise has many, many solutions1 . Its a job interview classic2 that a
significant number of candidates fail. Try your best!
1
http://www.tomdalling.com/blog/software-design/fizzbuzz-in-too-much-detail/
2
http://imranontech.com/2007/01/24/using-fizzbuzz-to-find-developers-who-grok-coding/
5. Write functions
In this chapter, youll 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 combination of several short and focused functions, a program will generally
be easier to understand and more modular than a monolithic one.
A function call triggers the execution of the function code. After its 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
myFunc(arg1, arg2, ...);
A third way to create an anonymous function is the more recent fat arrow syntax.
// Function call
myFunc(arg1, arg2, ...);
No matter how its created, each function should have a precise purpose and a well chosen
name (often including an action verb). JavaScript offers a lot of 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 its 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.
Heres 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. Heres the second part of our example program.
Write functions 38
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.
// ...
myFunction(); // Call myFunction
// ...
Calling a function triggers the execution of actions listed therein (the code in its body). After its
done, execution resumes at the place where the call was made.
Usefulness of functions
A complex problem is generally more manageable when broken down into simpler subproblems.
Computer programs are no exception to this rule. Written as a combination of several short and
Write functions 39
focused functions, a program will be easier to understand and to update than a monolithic 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 duplication1 ; instead of being
duplicated in several places, a piece of code can be centralized in a function and called from
anywhere when needed.
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 youll 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 of any type (number, string, etc). However, a function can return only
one value.
1
https://en.wikipedia.org/wiki/Duplicate_code
Write functions 40
Retrieving a functions 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.
function myFunction() {
// ...
// No return value
}
A function stops running immediately after the return statement is executed. Any
further statements are never run.
Lets simplify our example a bit by getting rid of the variable that stores the functions 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 these local variables outside the
function, you wont 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 functions 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, its a good thing! This means functions can be designed as autonomous
and reusable. Moreover, this prevents naming conflicts: allowing variables declared in different
functions to have the same name.
Parameter passing
A parameter is 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.
Lets 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.
Heres 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 youll soon discover,
anonymous functions are heavily used in JavaScript.
Heres 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 theres 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. Youll use them constantly in your programs.
The function Math.min() returns the minimum number among its arguments. The function
Math.random() generates a random number between 0 and 1.
This book will introduce many other JavaScript functions.
If you have difficulties coming up with a good 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.
Write functions 46
When its done, update the program so that it shows the square of every number between 0 and
10.
Writing 10 dumb calls to square() is forbidden! You know how to repeat statements,
dont you? ;)
Calculator
Complete the following program so that it offers the four basic arithmetical operations: addition,
subtraction, 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 secondary school
memories Or a Google click away :)
The value of number (Pi) is obtained with Math.PI in JavaScript.
You might want to use the exponentiation operator2 ** to perform computations.
console.log(2 ** 3); // 8: 2 * 2 * 2
console.log(3 ** 2); // 9: 3 * 3
2
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators
6. Create your first objects
This chapter will introduce objects and the way they are created and used in JavaScript.
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 a piece of information (number, string, etc) or a function.
In the latter 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
Whats 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 piece of information associated with the object
(the color of the pen) or an action (the pens 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"
};
As stated earlier, 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 its 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 followed by a comma , (except the last one).
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 objects property is an expression that produces a value. Such an expression can
be included in more complex ones. For example, heres 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
her name,
her health (number of life points),
her 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.
Create your first objects 53
As you can see, you can assign numbers, strings, and even other objects to properties!
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. Theres 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 objects properties to
create a description string.
Below is an alternative approach, using 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 adds 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 a crucial 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 objects 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 doesnt 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 arrays1 , a type of variable used in many computer programs
to store data.
TL;DR
An array represents a list 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
});
The push() method adds an element at the end of an array. The unshift() method adds
it at the beginning.
The pop() and splice() are used to remove elements from the array.
Introduction to arrays
Imagine you want to create a list of all the movies youve seen this year.
One solution would be to create several variables:
1
https://en.wikipedia.org/wiki/Array_data_type
Store data in arrays 60
If youre 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",
// ...
};
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 indeed a solution: use an array. An array is a data type that can store a set of
elements.
Creating an array
Heres 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.
Since an array may contain multiple elements, its 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 []:
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 is its last element.
Another way is to call the forEach() method on the array. It takes as a parameter a function
that will be applied to each array element.
myArray.forEach(myElement => {
// Use myElement to access each array element one by one
});
Heres 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 objects2 like
arrays. Here is its syntax.
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.
To add an element at the beginning of an array, use the unshift() method instead of push().
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.
Coding time!
Create all these programs in a generic fashion: the program output should reflect any update in
the arrays 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 DArtagnan value to the array.
Shows each array element using the forEach() method.
Remove poor Aramis.
Shows each array element using a for-of loop.
Store data in arrays 64
Sum of values
Write a program that creates the following array, then calculates and shows the sum of its values
(42 in that case).
Array maximum
Write a program that creates the following array, then calculates and shows the arrays maximum
value.
List of words
Write a program that asks the user for a word until the user 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 strings1 . Lets 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 strings are immutable2 : 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 return new converted
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.
The Array.from() method can be used to turn a string into an array that can be traversed
letter by letter with the forEach() method.
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
Lets recapitulate what we already know about strings:
console.log("ABC".length); // 3
const str = "I am a string";
const len = str.length;
console.log(len); // 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.
Its important to understand that once created, a string value never changes: strings are
immutable in JavaScript.
String comparison is case sensitive. Do indeed pay attention to your lower and
uppercase letters!
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 the loop needs to run once for each character in
the string.
The loop counter i ranges from 0 (the index of the strings 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 loop for an identical result.
As for arrays covered earlier, a 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 simpler than a standard for
loop.
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. Beware: these methods are case-sensitive.
console.log(song.startsWith("Honk")); // true
console.log(song.startsWith("honk")); // false
console.log(song.startsWith("Tonk")); // false
console.log(song.endsWith("men")); // true
console.log(song.endsWith("Men")); // false
console.log(song.endsWith("Tonk")); // false
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.
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 thats spelled the same way both forward and backward, ignoring punctuation, case,
and spacing.
TL;DR
Object-Oriented Programming, or OOP, is a programming paradigm1 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.
1
https://en.wikipedia.org/wiki/Programming_paradigm
Understand object-oriented programming 72
JavaScripts 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 by first searching its prototype, then
its prototypes 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 JavaScripts own prototype-based
OOP model.
const aurora = {
name: "Aurora",
health: 150,
strength: 25,
xp: 0,
aurora.strength += 10;
console.log(aurora.describe());
To make the game more interesting, wed like to have more characters in it. So here comes
Glacius, Auroras fellow.
const glacius = {
name: "Glacius",
health: 130,
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 whats 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 lets create a Character class to express what a
character is.
Understand object-oriented programming 74
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} as strength and ${this.xp} XP points`;
}
}
A class is created with the class keyword, followed by the name of the class (usually
starting with an uppercase letter).
Contrary to object literals, there is no separating punctuation between the elements inside
a class.
A class can only contain 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 75
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.
Heres 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.
Heres an example (borrowed from Kyle Simpsons great book series You Dont Know JS2 ).
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 doesnt exist in anotherObject.
If the prototype of an object does not have a desired property, then the search continues in the
objects 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, an attempted access to the property 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.
2
https://github.com/getify/You-Dont-Know-JS/blob/master/this%20%26%20object%20prototypes/ch5.md
Understand object-oriented programming 77
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!
Following is 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 falls below zero, the character is considered
dead and cannot attack anymore. Its vanquisher receives a fixed number of 10 experience points.
First, lets add the capability for our characters to fight one another. Since its 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(
3
https://en.wikipedia.org/wiki/Syntactic_sugar
Understand object-oriented programming 78
Now we can introduce a monster in the game and make it fight our players. Heres the rest of
the final code of our RPG.
monster.attack(aurora);
monster.attack(glacius);
aurora.attack(monster);
glacius.attack(monster);
Understand object-oriented programming 79
console.log(aurora.describe());
console.log(glacius.describe());
Execution result
The previous program is a short example of Object-Oriented Programming (in short: OOP),
a programming paradigm4 (a programming style) based on objects containing both data and
4
https://en.wikipedia.org/wiki/Programming_paradigm
Understand object-oriented programming 80
behavior.
Coding time!
Dogs
Complete the following program to add the definition of the Dog class.
Dogs taller than 60 emote "Grrr! Grrr!" when they bark, other ones yip "Woof!
Woof!".
Execution result
Character inventory
Improve the example RPG to add character inventory management according to the following
rules:
Understand object-oriented programming 81
Execution result
Account list
Lets build upon a previous account object exercise. A bank account is still defined by:
A name property.
A balance property, initially set to 0.
Understand object-oriented programming 82
A credit method adding the value passed as an argument to the account balance.
A describe method returning the account description.
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 favoring local over global variables.
A pure function depends solely on 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 a parameter or returning it) is called a 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.
Discover functional programming 85
Execution result
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 everywhere 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 a program grows
in size and complexity, it becomes 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());
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 limits 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 programs 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 that 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.
Discover functional programming 89
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, theres 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.
Lets refactor our example code to introduce pure functions.
let ratingSum = 0;
for (const movie of movies) {
ratingSum += movie.imdbRating;
}
return ratingSum / movies.length;
};
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.
Heres how our titles() could be rewritten using map(). Look how the function code is now
more concise and expressive.
Discover functional programming 91
The map() and filter() method can be used together to achieve powerful effects. Look at this
new version of the bestTitles() function.
Discover functional programming 92
The first one is the function associated to reduce() and called for each array element. It
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).
Heres how to apply reduce() to calculate the average rating of a movie list.
Discover functional programming 93
Another possible solution is to compute the rating sum by using map() before reducing an array
containing only movie ratings.
// ...
// 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 a higher-order function.
Check out this final version of our example program.
console.log(titles(movieList));
Discover functional programming 94
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
},
{
1
https://www.w3.org/community/webed/wiki/A_Short_History_of_JavaScript
2
https://en.wikipedia.org/wiki/Scheme_(programming_language)
Discover functional programming 95
console.log(moviesBefore2000);
Execution result
Government forms
Complete the following program to compute and show the names of political forms ending with
"cy".
Discover functional programming 96
const governmentForms = [
{
name: "Plutocracy",
definition: "Rule by the wealthy"
},
{
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.
Student results
Heres a program that shows female students results (name and average grade).
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);
Discover functional programming 98
Refactor it using functional programming. Execution result must stay the same.
Execution result
11. Project: a social news program
Now that youve discovered the basics of programming, lets go ahead and build a real project.
Objective
The goal of this project is to build a basic social news program. Its users 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).
If a new link URL does not start with "http://" or "https://", "http://" is automatically
added to its beginning.
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 shown links.
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 shown 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 Web1 (or Web) is an information space built on top of the Internet2 . Web
resources are accessible via their URL3 , and can contain hyperlinks4 to other resources.
A web page is a document suitable for the Web. Creating web pages usually involves
three technologies: HTML5 to structure the content, CSS6 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, such as: 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>
1
https://en.wikipedia.org/wiki/World_Wide_Web
2
https://en.wikipedia.org/wiki/Internet
3
https://en.wikipedia.org/wiki/Uniform_Resource_Locator
4
https://en.wikipedia.org/wiki/Hyperlink
5
https://en.wikipedia.org/wiki/HTML
6
https://en.wikipedia.org/wiki/Cascading_Style_Sheets
Whats 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 Language12 , 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>
7
https://en.wikipedia.org/wiki/World_Wide_Web
8
https://en.wikipedia.org/wiki/Internet
9
https://en.wikipedia.org/wiki/Uniform_Resource_Locator
10
https://en.wikipedia.org/wiki/Hyperlink
11
https://en.wikipedia.org/wiki/Web_browser
12
https://en.wikipedia.org/wiki/HTML
Whats a web page? 105
Display result
CSS
CSS, or Cascading Style Sheets16 , 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.
#rude {
font-family: monospace;
text-transform: uppercase;
}
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.
Coding time!
You can skip this exercise if you have prior experience with HTML and CSS.
Expected result
21
https://developer.mozilla.org/en-US/docs/Learn/Getting_started_with_the_web/Dealing_with_files
22
https://developer.mozilla.org/en-US/docs/Learn/Getting_started_with_the_web/HTML_basics
23
https://developer.mozilla.org/en-US/docs/Learn/Getting_started_with_the_web/CSS_basics
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 pages structure.
The DOM is also 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 109
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 programmatic access to its structured representation of a displayed web
page. Using this interface, you can dynamically update the page by 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 its 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 Consortium1 (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 its an HTML tag.
The childNodes property of an element node is not a real JavaScript array, but rather
a NodeList2 object. Not all of the standard array methods are applicable to it.
The following code would display the first child of the body node.
Execution result
Wait Why isnt the first child node h1, since thats the first element in the bodys
HTML?
Thats 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. Lets double check that:
Execution result
To eliminate these text nodes between tags, you could have written the HTML page in a more
condensed way.
Its better, however, to take the text nodes between tags into account than to sacrifice visibility
and code indentation.
Discover the DOM 113
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, which can further be converted to an array with Array.from(). The latter method
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 elements
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 118
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.
Well stick to it throughout this book.
1
https://developer.mozilla.org/en-US/docs/Web/API/NodeList
Traverse the DOM 119
Execution result
Execution result
Beware: contrary to others, the getElementById() method does not contain any 's'
after the word "Element".
This syntax is a little clunky though. Lets 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 121
// All paragraphs
console.log(document.querySelectorAll("p").length); // 3
Check the Mozilla Developer Network2 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
2
https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors
3
https://jsperf.com/getelementsbyclassname-vs-queryselectorall/195
Traverse the DOM 122
HTML content
The innerHTML property will retrieve the HTML content 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 123
Execution result
Traverse the DOM 124
Attributes
The getAttribute() method can be applied to a DOM element and will return the value of a
given attribute.
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
}
Traverse the DOM 125
Classes
In a web page, a tag can have multiple classes. The classList property retrieves a DOM elements
list of classes.
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'."); // W\
ill be shown
} else {
console.log("The element with ID 'ancient' does not have the class 'wonders\
'.");
}
This is only a part of the DOM traversal API. For more details, check the Mozilla
Developer Network4 .
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.
4
https://developer.mozilla.org/en-US/docs/Web/API/Element
Traverse the DOM 126
Handling attributes
Here is the description of several musical instruments.
Expected result
Traverse the DOM 127
Add the following new instrument at the end of the HTML list, then check your programs 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 tests if an element designated by its
ID has a class. The function shows true, false or an error message if the element cant be found.
Expected result
15. Modify page structure
Lets see how to use JavaScript to modify a web page once its 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 elements 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 elements 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 is not intended to access an elements style. You should use the
getComputedStyle() function instead.
Manipulating the DOM with JavaScript should be done sparingly so that page performance
doesnt suffer.
Example page
The examples in the next paragraphs use the HTML code below.
Modify page structure 130
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. Well 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,
youll have no content!
When using innerHTML, you put HTML content into strings. To keep your code readable
and avoid mistakes, you should only use innerHTML to make small content changes.
Youll discover more versatile solutions below.
Modify page structure 131
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 page structure 132
Execution result
For example, suppose you want to add the language Python to the list of languages on our
page. Heres the JavaScript code youd use to do so.
Execution result
Modify page structure 133
// ...
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 page structure 136
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.
Execution result
Removing a node
Lastly, you can delete a node thanks to a method called removeChild(), to which youll pass the
node-to-be-removed as a parameter.
Execution result
Modify page structure 138
Styling elements
JavaScript not only lets you interact with your web page structure, but it also lets you change
the style of elements. Its 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 were adjusting via CSS 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 theyre 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 elements font-family and background-color
properties.
Modify page structure 139
// ...
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 paragraphs 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 page structure 142
<h3>Some newspapers</h3>
<div id="content"></div>
Write a program that shows on the 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 shows on the 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 page structure 143
Use the HTML <dl> tag to create the list (more on this tag3 ). 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, and then asks for the new background
color. The page is then updated accordingly.
3
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/dl
Modify page structure 144
<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 width of the element
identified by content.
Modify page structure 145
Execution result
16. React to events
To make a web page interactive, you have to respond to user actions. Lets 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 up to 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 with 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 users 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 generally anytime a program needs to interact with a user.
A first example
Heres some starter HTML code.
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 (information 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 this
object 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 generally 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 149
The following example shows in the console the character associated to a pressed key. The
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), youll use
the keydown and keyup events. This example uses the same function to manage two events. This
time, the keys 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 151
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 153
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 represents
the browser window) to know when this happens. This avoids messy situations where JavaScript
interacts with pages that arent 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 stan-
dard 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 hierarchy.
React to events 154
Heres 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 buttons click handler prevents the click event from propagating every-
where in the DOM tree.
React to events 155
Execution result
Now clicking on the links shows a dialog instead of navigating to its target.
Execution result
React to events 156
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 deactivate button stops 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 updates the background color of all div tags according
to the key (R, Y, G or B) pressed by the user.
React to events 157
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 desserts name when clicking on it.
React to events 158
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 159
Execution result
17. Manipulate forms
JavaScript lets you manage forms defined within your web page, in order to further improve
interactivity.
TL;DR
A form lets users input data through a web page. Inputted data is usually sent to a web
server. Before data gets sent off, you can use JavaScript to interact with the form data and
validate it.
Text zones (input type="text"> or <textarea>) each have a value property to access the
inputted value.
When a text field becomes the input target, this field has the focus. The focus and blur
events are triggered when the field gets or loses the focus, respectively. The focus() and
blur() methods can update the focus target programmatically.
Checkboxes, radio buttons, and dropdown lists generate change events whenever a user
modifies their choice.
The DOM element that corresponds to the form has an elements property that lets you
access its input fields programmatically.
Submitting a form triggers a submit event on the form DOM element. You can prevent
the sending of form data to the server by using the preventDefault() method on the
associated Event object.
Any modification of a text field triggers an input event, which can be used to validate its
data as the user enters it.
A regular expression is a pattern to which strings can be compared. Regular expressions
are often used to perform fine-grained validations of form data.
Form recap
Forms enhance web pages by allowing users to input information through text fields, check
boxes, dropdown menus, and more. Inside a web page, a form is defined with a <form> HTML
tag, and within this tag, you have your different <input> tags, <select> tags, or <textarea>
tags.
If forms are totally new to you, the Mozilla Developer Network has a great intro
aptly named Your first HTML form1 . For a more general recap on forms, check out
this course chapter2 on OpenClassrooms.
1
https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Your_first_HTML_form
2
https://openclassrooms.com/courses/build-your-website-with-html5-and-css3/forms
Manipulate forms 161
Form fields
Example form
Lets start with a simple form that allows users to sign up for a service.
<form>
<h1>Signup form</h1>
<p>
<label for="username">Username</label>:
<input type="text" name="username" id="username" required>
<span id="usernameHelp"></span>
</p>
<p>
<label for="password">Password</label>:
<input type="password" name="password" id="password" required>
<span id="passwordHelp"></span>
</p>
<p>
<label for="emailAddress">Email address</label>:
<input type="email" name="emailAddress" id="emailAddress" required placeh\
older="user@domain">
<span id="emailHelp"></span>
</p>
<p>
<input type="checkbox" name="confirmation" id="confirmation">
<label for="confirmation">Send me a confirmation email</label>
</p>
<p>
<input type="radio" name="subscription" id="newsroom" value="newspromo">
<label for="newsroom">Subscribe me to newsletters and promotions</label>
<br>
<input type="radio" name="subscription" id="news" value="news">
<label for="news">Subscribe me only to the newsletter</label>
<br>
Manipulate forms 162
Display result
This example contains multiple input zones: text, checkboxes, radio buttons, a dropdown menu,
Manipulate forms 163
as well as submit and cancel buttons. Well learn how to deal with each of these elements with
JavaScript.
You might have noticed that the <form> tag doesnt have the usual action and
method attributes. These attributes allow you to define the requested server resource
when the form is submitted by the user. Since our form will only be handled by
JavaScript in the browser, theyre not necessary.
Text zones
A text field allows a user to input text on single or multiple lines. You have two options for
defining text fields: a single-line text field is defined in HTML as <input type="text">, and a
multi-line text input field will be defined via <textarea> instead.
Heres the extract from the above code that lets users input a username.
<label for="username">Username</label>:
<input type="text" name="username" id="username" required>
<span id="usernameHelp"></span>
In JavaScript, you can access the value of a text field by using the value property of the
corresponding DOM element. By setting a new value for this property, youll modify the value
shown in the text field.
The following example adds the value MyCoolUsername to the text field.
Handling focus
When a text zone is selected, it becomes the focused area of the form. You may have noticed
field borders turning blue or other effects when youre accessing a particular input area. This
helps you know where you are in the form. A user clicking on a text field (or tabbing down into
it) kicks off a focus event. Additionally, a focus event triggers a blur event on the field that
previously had the focus.
You can use these events to show the user tips related to the current text field, as in the following
example:
Manipulate forms 164
By selecting the username input field, youll see a helpful message in the HTML <span> defined
specifically for that purpose and initially empty.
Execution result
From JavaScript code, you can modify the input target by calling the focus() (to give focus) and
blur() methods (to remove it) on a DOM element.
Youll learn how to validate text that a user inputs (to make sure it fits certain
criteria) later in this chapter.
Choice elements
You often see form elements that allow users to make a choice among multiple possibilities. A
change event will be kicked off once a user changes their choice.
Checkboxes
You can add checkboxes to your HTML form by using the tag <input type="checkbox">.
Heres the code from the example form that offers a user the choice to receive a confirmation
email (or not).
Whenever the box is checked or unchecked by the user, a change event is kicked off. The Event
object associated to this event has a checked boolean property that gives the new state of the
field (checked or not checked).
The below code handles the change event on the checkbox to show a message in the console.
Manipulate forms 165
Execution result
Radio buttons
Radio buttons allow users to make a choice out of multiple possibilities. You create radio buttons
with <input type="radio"> tags, which have the same name attribute and different value
attributes.
Heres the extract from the example form that lets a user select between three radio buttons, each
representing a subscription option.
The following JavaScript code adds a message to the console when the radio button selection
changes.
Manipulate forms 166
Execution result
The target.value property of the change event matches the value attribute of the newly selected
<input> tag.
Dropdown lists
A dropdown list is created using the <select> tag (for the menu overall) in which you can add
<option> tags for possible choices.
Heres the code extract from above that lets users choose a nationality:
<label for="nationality">Nationality</label>:
<select name="nationality" id="nationality">
<option value="US" selected>American</option>
<option value="FR">French</option>
<option value="ES">Spanish</option>
<option value="XX">Other</option>
</select>
The following code uses the change event triggered on the dropdown list to show the new choice
made by the user.
Manipulate forms 167
Execution result
Like with radio buttons, the target.value property of the change event matches the value
attribute of the <option> tag associated with the new choice not the text shown in the
dropdown list!
Submitting a form
A form will be submitted when a user clicks on the submit button, which will have an <input
type="submit"> tag. An <input type="reset"> tag shows a button that resets the form data.
Here are the two buttons from the sample form.
Manipulate forms 168
When a user submits a form, the default behavior of the browser is to contact a web server
and request the resource identified by the action attribute of the <form> tag, sending form data
along the way. Prior to this, a submit event is triggered on the DOM element corresponding to
the form. By adding a handler for this type of event, you can access form data before it gets sent.
You can cancel the request to the server by calling the preventDefault() method on the Event
object associated to the event.
The following code shows in the console all user input in the form, then cancels the request to
the server.
if (e.target.elements.confirmation.checked) {
console.log("You asked for email confirmation");
} else {
console.log("You didn't asked for email confirmation");
}
switch (e.target.elements.subscription.value) {
case "newspromo":
console.log("You are subscribed to newsletters and promotions");
break;
case "news":
console.log("You are subscribed to newsletters only");
break;
case "no":
console.log("You are not subscribed to anything");
break;
default:
console.error("Unknown subscription code");
}
switch (e.target.elements.nationality.value) {
case "US":
console.log("Hello! You are a US citizen");
break;
case "FR":
console.log("Bonjour! You are a French citizen");
break;
Manipulate forms 169
case "ES":
console.log("Hola! You are a Spanish citizen");
break;
default:
console.log("Your nationality is unknown");
}
e.preventDefault(); // Cancel form data sending
});
Form validation
Checking data inputted by users before it gets sent to a server is a major use of JavaScript with
web forms. Using form validation, you can improve the users experience by immediately alerting
him on problems with their input. This is also an efficient way to prevent useless server requests
with wrong data.
Validation can happen in several ways:
This last technique only involves adding validation in the submit event handler for the form:
you already know how to do that. Well look at the other two techniques one at a time, using the
same example form as before.
Instant validation
Validation while a user is inputting information is based on input events, which are triggered
on an input zone each time its value changes.
Manipulate forms 170
The following code example adds an input event handler on the password field. This handler
checks the length (number of characters) of the password being typed and shows a message to
the user with specific content and color.
Execution result
Post-input validation
A text zones input is considered finished once focus is lost on the zone, which kicks off a blur
event that you can use to trigger validation.
Lets imagine that you want to validate the presence of an @ character in the email address entered
by a user. Heres the JavaScript code which shows this validation.
Execution result
Regular expressions
The previous validations were quite primitive: many strings containing a @ character are not
valid email addresses. To perform more advanced checks, you can use a powerful tool: regular
expressions.
A regular expression defines a pattern to which strings are compared, searching for matches.
Many programming languages support them. A powerful addition to a programmers toolbelt,
they can nonetheless take quite a bit of time to be comfortable with. What follows is just an
introduction to the vast domain of regular expression.
Lets get started by trying to create a regular expression checking for the presence of an @
character inside a string. Heres the associated JavaScript code.
A JavaScript regular expression is defined by placing its pattern between a pair of / characters.
Its an object whose test() method checks matches between the pattern and the string passed
as a parameter. If a match is detected, this method returns true, and false otherwise.
The following table presents some of the numerous possibilities offered by regular expressions.
Brackets [] define a character interval. Any string with at least a character in this interval
will match the pattern.
The [a-z] and [A-Z] patterns are used to search for the presence of any letter, respectively
lowercase and uppercase.
The [0-9] and \d patterns are essentially identical and match a digit in a string.
The . character replaces any one character.
The \ (backslash) character indicates that the following character should be searched as-if.
. For example, \. is used to match the . character itself.
The + character matches one or several instances of the preceding expression.
The * character matches zero, one, or several instances of the preceding expression.
The site https://regex101.com is useful to understand, test and debug regular expres-
sions.
Lets get back to our example and check the email address field. Heres a possible regular
expression (among many others) to test it against: /.+@.+\..+/.
Before reading further, can you decode this pattern to understand what conditions a
string must respect to match it?
In other words, any string of the form [email protected] will match this pattern. This is not the end-all,
be-all way to validate an email address, but its a start.
Check out how to put this solution into practice.
Manipulate forms 173
Execution result
Coding time!
Password checker
Start with the following HTML code.
<form>
<p>
<label for="password1">Enter the password</label>:
<input type="password" name="password1" id="password1" required>
</p>
<p>
<label for="password2">Confirm the password</label>:
<input type="password" name="password2" id="password2" required>
</p>
<p id="passwordHelp"></p>
Write the JavaScript code that validates the password when the user submits the form. The
validation rules are as follow:
The validation result must be shown on the page with an appropriate message in each case.
Execution rrsult
Character list
The TV show Game of Thrones is about the struggle for power between several noble families.
In this exercise, youll have to show characters belonging to the house selected by the user.
Here is the associated HTML code.
<p>
<ul id="characters"></ul>
</p>
Execution result
Autocomplete
In this exercise, youll have to assist the user in selecting a country. As he enters the country
name in an input box, the page shows a list of corresponding countries. Clicking on a suggested
country replaces the value in the input box.
To keep things simple, only countries starting with a "A" letter are taken into
account.
// Country list
const countryList = [
"Afghanistan",
"Albania",
"Algeria",
"Andorra",
"Angola",
"Anguilla",
"Antarctica",
"Antigua-and-Barbuda",
"Argentina",
"Armenia",
"Aruba",
"Australia",
"Autria",
"Azerbajan"
];
Execution result
18. Animate elements
This chapter will get you started with JavaScript for animations! Well see how to kick off
animations that should run repeatedly or should stop at a certain point.
TL;DR
The setInterval() function kicks off a repeated action and is called at regular intervals.
The clearInterval() function stops a repeated action that was launched with setInter-
val().
The setTimeout() function executes an action once after a certain delay.
The requestAnimationFrame() function asks the browser to execute a function that
updates the animation as soon as possible. This works well for real-time animations. The
cancelAnimationFrame() function stops an in-progress animation that was launched with
requestAnimationFrame().
You can also create web animations via CSS.
Click here1 to see it in action. It works as expected Kind of: the countdown never stops. Well
fix this a little later.
1
https://codepen.io/bpesquet/pen/RVWLeY?editors=1010
Animate elements 179
Calling Number() in the function code is mandatory: it converts the counter string
into a number, which endows it with subtraction functionality.
The call to setInterval() triggers a repeated action. This function lets you call a function at
regular intervals. Its parameters are the function to call and the time in milliseconds between
each call. The returned value is an ID for the repeated action, which can be used to further
modify it.
Once the countdown has finished, we call the setTimeout() function to set a new page title after
a 2 second (2000 milliseconds) delay.
The setTimeout() function lets you execute a function once after a particular delay, expressed
in milliseconds.
<div id="frame">
<div id="block"></div>
</div>
#frame {
border: 1px solid red;
}
#block {
width: 20px;
height: 40px;
background: red;
position: relative;
}
Display result
And here is the JavaScript code that lets you move the red block.
Animate elements 182
Start an animation
The example code defines a function called moveBlock() which moves the block horizontally to
the right. It grabs the current position of the blocks left border than adds the value contained in
the movement variable. Next, it calls the requestAnimationFrame() method to keep the animation
going.
Position values are written in pixels. These are the strings you saw that resemble XXpx, which
requires the use of the JavaScript parseFloat() function to convert numeric values before
making calculations.
Dont use Number() to convert a string with "px" into a numerical value. This wont
work, and youll get a NaN value (Not a Number) as a result!
The requestAnimationFrame() function lets you ask the browser to execute a function as soon
as possible, which updates the animation. Its the browsers job to make the animation as smooth
as possible. The returned value of requestAnimationFrame() is an ID for the animation, which
can be used to further modify it.
Here is how requestAnimationFrame() is used in combination with an animation function.
4
https://codepen.io/bpesquet/pen/RVWxbW
Animate elements 183
// Animation start
let animationId = requestAnimationFrame(animate);
Stop an animation
Lets now see how to stop the block before it reaches the border of the frame that contains it.
Well have to verify that the left border position is less than the width of the frame, bearing in
mind the thickness of the block itself.
Heres the updated JavaScript code.
// Move the block to the right, all the way to the end of the frame
const moveBlock = () => {
// Convert the left position of the block (value of the form "XXpx") to a n\
umber
const xBlock = parseFloat(getComputedStyle(blockElement).left);
// Convert the width of the frame (value of the form "XXpx") to a number
const xMax = parseFloat(getComputedStyle(frame).width);
// If the block isn't already to the end of the frame
if (xBlock + blockWidth <= xMax) {
// Block movement
blockElement.style.left = (xBlock + movement) + "px";
animationId = requestAnimationFrame(moveBlock);
}
else {
// Cancel the animation
cancelAnimationFrame(animationId);
}
};
// Stop an animation
cancelAnimationFrame(animationID);
Lets check out how to get a similar effect as the previous example by using CSS instead of
JavaScript. Remove any JavaScript code from your example and modify your CSS code as follows.
#frame {
border: 1px solid red;
}
#block {
width: 20px;
height: 40px;
background: red;
position: relative;
margin-left: -20px; /* Negative margin to simplify position calculations */
animation-name: moveBlock; /* Name of animation */
animation-duration: 6s; /* Length of animation */
animation-fill-mode: forwards; /* Let the block in its final position */
}
@keyframes moveBlock {
from {
/* Initial position: to the left of the frame (taking negative margin int\
o account) */
left: 20px;
}
to {
/* Final position: within the right side of the frame (taking negative ma\
5
https://codepen.io/bpesquet/pen/rmOpZE
Animate elements 185
Use setInterval() if the animation isnt in real-time and should just happen at regular
intervals.
Favor CSS if the animation happens in real-time and can be managed with it.
Use requestAnimationFrame() for any other case.
Coding time!
Chronometer
Write an interactive web page with a button to start and stop a chronometer counting the number
of elapsed seconds.
Bouncing ball
The goal of this exercise is to make a basketball bounce across the screen. You can download the
ball image here7 .
Start with the following HTML and CSS content.
6
https://codepen.io/bpesquet/pen/wdKyQb?editors=1100
7
https://raw.githubusercontent.com/bpesquet/thejsway/master/resources/basketball.jpg
Animate elements 186
<p>
<button id="start">Start</button>
<button id="stop" disabled>Stop</button>
</p>
<div id="frame">
<!-- Update the "src" attribute if you downloaded the image locally -->
<img id="ball" src="https://raw.githubusercontent.com/bpesquet/thejsway/mas\
ter/resources/basketball.jpg">
</div>
#ball {
position: relative;
left: 0px;
}
Write the JavaScript code that makes the ball bounce horizontally.
Execution result
Create a variable with values 1 or -1 to know in which direction the ball should move.
19. Project: a social news web page
You know now enough JavaScript and DOM to go ahead and create interactive web pages for
real!
Objective
This project builds upon the social news program you created previously. This time, the objective
is to make a social news web page.
The general idea and page layout for this project are inspired by the Discover Meteor
book1 s example application.
Functional requirements
A link is defined by its title, its URL and its author (submitter).
If a new link URL does not start with "http://" or "https://", "http://" is automatically
added at its beginning.
The web page displays a list of at least three already existing links.
A button exists for the user to submit a new link. When clicked, a form appears before the
link list to input the new link properties (author, title and URL).
In this form, all link fields are mandatory.
When the new link is validated by the user, it is displayed at the top of the link list,
replacing the form. A message indicates the success of the operation, then disappears after
two seconds.
Technical requirements
You should reuse any useful code from the previous project.
All your code should be correctly indented.
Names should be wisely chosen and adhere to the camelCase convention.
Code duplication should be avoided.
1
https://www.discovermeteor.com/
Project: a social news web page 188
Starter code
Because this is first and foremost a JavaScript project, here is the complete HTML/CSS code of
the web page. It is also online as a CodePen2 .
This web page uses the Bootstrap3 framework to improve presentation and make it
responsive. However, Bootstrap knowledge is not mandatory to achieve the desired
result. You can pretty much ignore it and code ahead.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.\
7/css/bootstrap.min.css">
<link href="../css/publink.css" rel="stylesheet" type="text/css">
<title>A social news web page</title>
</head>
<body>
<div class="container">
<div id="content">
<!-- Dynamic content goes here -->
</div>
</div>
</html>
body {
background-color: #eee;
}
.linkForm {
margin-bottom: 20px;
}
Expected result
Here are a few screenshots of the expected result.
Link list
Project: a social news web page 191
TL;DR
Data exchanges on the Web follow a request/response paradigm. A client issues a request
to a server, which process it and sends back its result to the client.
HTTP (HyperText Transfer Protocol), is the protocol that allows two machines to com-
municate with each other on the web. Its secured version is HTTPS.
HTTP is based on textual commands. The HTTP method defines the type of the request.
The main HTTP methods are GET to access a resource and POST to push some information
on the server.
An HTTP response contains a status code indicating the result of the request: 200 for
success, 404 for a resource not found, etc.
Web resources are uniquely addressed by their URL (Uniform resource locator). An URL
is a text of the form http://www.mywebsite.com/myresourcepath/myresource.
In a traditional web development scenario, user actions on a page trigger a full reload after
a synchronous request to a server. Another web development model, nicknamed AJAX
(Asynchronous JavaScript and XML), uses JavaScript and asynchronous HTTP requests
to fetch data when needed and update only the desired portions of the page. This enables
the creation of web applications, aiming to offer the user experience of a native app.
Cross-domain AJAX requests are only possible if the server has been configured to accept
them by setting on cross-origin resource sharing (CORS).
JSON (JavaScript Object Notation), a textual syntax for describing structured information,
has replaced XML as the data format of the web. A JSON document is a set of name/value
pairs.
Web servers
To be online, a web site has to be published on a server. This is a special kind of machine whose
task is to listen and answer to the demands of clients. A server that publishes resources on the
Web is logically called a web server.
More precisely, a web server machine runs a particular software program (also called a web
server) able to publish web sites. The most popular ones are Apache3 , Microsoft IIS4 and nginx5 .
Web clients
The machine asking a server for a resource is called a web client. Actually, the real client is a
software program running on the machine. a well-known type of web client is the browser, a
program specialized in displaying web pages. Famous web browsers include Mozilla Firefox6 ,
Chrome7 , Safari8 and Opera9 .
Not all web clients are browsers, through. For example, search engines robots and mobile
applications also contact servers and ask them for content.
1. The exchange is started by the client, which sends a request to the server to access a
particular web resource.
3
http://httpd.apache.org/
4
http://www.iis.net/
5
http://nginx.org
6
https://www.mozilla.org/firefox
7
https://www.google.com/chrome/browser/
8
https://www.apple.com/safari/
9
http://www.opera.com/fr
Web development 101 196
To understand each other, web clients and servers use a common protocol: HTTP.
This HTTP request comes under the form as a multi-line piece of text similar to the following
one.
GET / HTTP/1.1
Host: xkcd.com
Accept: text/html
User-Agent: Mozilla/5.0 (Macintosh)
...
The HTTP method (the request type, also named command). Here, the GET method
indicates a resource access request.
The requested resource. Here, / (root symbol) indicates a request for the default document.
The HTTP protocol version, here 1.1.
The other lines of text are called header fields. They give more information about the client
request: server name (Host), accepted content types (Accept), client software details (User-
Agent). They are many other possible header fields.
The main HTTP methods are GET to access a resource and POST to push some information on the
server. Other ones exist, such as HEAD, PUT or DELETE.
The HTTP response sent by the server looks something like this.
HTTP/1.1 200 OK
Date: Fri, 22 Apr 2017 18:05:05 GMT
Server: Apache/2.2
Content-Type: text/html
<html>
<!-- HTML code of the page -->
<!-- ... -->
</html>
The first line contains the response status: a three-digit number indicating the request result.
Other lines are header fields (Date, Content-Type, etc) giving additional info about the response.
An HTTP response might also include data. In this example, it contains the HTML code of the
web page corresponding to the requested resource.
Web development 101 198
For a more in-depth presentation of the HTTP protocol, head over to the Mozilla
Developer Network10 .
An address like this one is called an URL, or Uniform Resource Locator. An URL uniquely
describes a web resource and the way to request it.
User actions on the page are intercepted through JavaScript event handlers.
HTTP requests are sent to the server without interrupting the navigation on the page.
Only the needed portions of the page are updated with the requests results.
Albeit more challenging, this web development model can lead to limited resource loads,
improved interactivity and a user experience nearly on par with native applications.
The set of technologies enabling the creation of web applications is codenamed AJAX (Asyn-
chronous JavaScript and XML). An AJAX call is an asynchronous HTTP request made to retrieve
or send data from/to a server.
10
https://developer.mozilla.org/en-US/docs/Web/HTTP/Overview
Web development 101 199
Cross-domain requests
For security reasons, many websites have a conservative policy regarding AJAX requests. This
same origin policy states that requests are limited to their origin domain: "http://mysite"
cannot send a request to "http://anothersite". This prevents some servers to be accessible
via AJAX calls.
Enabling cross-domain requests is done by setting on cross-origin resource sharing (CORS) in
the server configuration.
For more information about this topic, check out this MDN article11 .
{
"cars": [
{
"model": "Peugeot",
"color": "blue",
"registration": 2012,
"checkups": [2015, 2017]
},
{
"model": "Citron",
"color": "white",
"registration": 1999,
11
https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
Web development 101 200
A JSON document is a set of name/value pairs. Name are always within double quotes "". Values
can be numbers, strings, booleans, arrays or objects.
Many programming languages have native support for the JSON format Including JavaScript,
of course!
21. Query a web server
This chapter will teach you how to retrieve data from a web server through HTTP requests.
TL;DR
HTTP requests sent to a web server need to be asynchronous to prevent blocking the
client application while waiting for the servers response.
The JavaScript fetch() method is replacing XMLHttpRequest as the go-to way of creating
an asynchronous request. Its then() and catch() methods respectively handle the success
and failure of the request.
The fetch() method demonstrates the use of promises to write asynchronous code in
JavaScript. A promise is a wrapper for an operation whose result might be available in
the future. It is either pending (initial state), fulfilled (operation completed successfully)
or rejected (operation failed).
JavaScript deals with JSON content with the JSON.parse() (to transform a JSON text into
an object) and JSON.stringify() method (to do the opposite).
The result of a call to fetch() is an HTTP Response object. Its text() and json() methods
are used to read content as plain text or JSON data. These two methods return a promise
that resolves either as a string or as JSON.
You might encounter JavaScript code that uses an object called XMLHttpRequest
to perform HTTP operations. This is a more ancient technique now replaced by
fetch().
A JavaScript promise is an object with then() and catch() methods. then() is called when the
promise is fulfilled. It takes the operation result as a parameter. On the contrary, catch() is
called when the promise is rejected.
Whats great about promises is that they can be chained together. Heres how you could perform
a series of asynchronous operations in JavaScript.
getData()
.then(a => filterData(a)) // Called asynchronously when getData() returns
.then(b => processData(b)) // Called asynchronously when filterData() retur\
ns
.then(c => displayData(c)) // Called asynchronously when processData() retu\
rns
// ...
C++;Java;C#;PHP
fetch(
"https://raw.githubusercontent.com/bpesquet/thejsway/master/resources/langu\
ages.txt"
)
.then(response => response.text()) // Access and return response's text con\
tent
.then(text => {
console.log(text); // Display file content in the console
});
Execution result
The result of the asynchronous HTTP request created by fetch() comes under the the form of
a Response object. This object has several methods to deal with the response of the HTTP call.
The text() method used in this example reads the responses text content and returns another
promise. Its result is managed by the second then() method, which simply displays the files
textual content in the console.
To learn more about the Response object, consult, as usual, the Mozilla Developer Network1 .
fetch("http://non-existent-resource")
.catch(err => {
console.error(err.message);
});
1
https://developer.mozilla.org/en-US/docs/Web/API/Response
Query a web server 204
Execution result
Execution result
Execution result
[
{
"title": "The Wolf of Wall Street",
"year": "2013",
"author": "Martin Scorsese"
},
{
"title": "Inside Out",
"year": "2015",
"author": "Pete Docter"
},
{
"title": "Babysitting",
"year": "2013",
"author": "Philippe Lacheau and Nicolas Benamou"
}
]
Heres how to retrieve this file from its URL and display each movie title in the console.
Query a web server 207
fetch(
"https://raw.githubusercontent.com/bpesquet/thejsway/master/resources/movie\
s.json"
)
.then(response => response.json()) // Access and return response's JSON con\
tent
.then(movies => {
// Iterate on the movie array
movies.forEach(movie => {
// Display title of each movie
console.log(movie.title);
});
})
.catch(err => {
console.error(err.message);
});
Execution result
The json() method of the HTTP Response object returns a promise that resolves with the result
of parsing the response text as JSON. As such, the movies parameter of the second then() is a
plain JavaScript array that can be iterated upon.
Coding time!
Language list
The objective of this exercise is to display the languages of the previous file languages.txt on a
web page. Here is the starter HTML code.
Query a web server 208
Write the JavaScript code that fetches the file from the web server and fills the HTML list.
Expected result
Famous paintings
In this exercise, youll show information about some famous paintings on a web page table. Infor-
mation about the paintings is located at URL https://raw.githubusercontent.com/bpesquet/thejsway/maste
and has the following content.
[
{
"name": "The Starry Night",
"year": "1889",
"artist": "Vincent Van Gogh"
},
{
"name": "The Scream",
"year": "1893",
"artist": "Edvard Munch"
},
{
"name": "Guernica",
"year": "1937",
"artist": "Pablo Picasso"
}
]
Write the JavaScript code that fills a table with details about the paintings.
Expected result
22. Use web APIs
In this chapter, youll learn how to leverage real-world web services in your applications.
TL;DR
An API or Application Programming Interface is a set of well-defined services offered
by a software program or service to others. Developers use them to integrate external
technologies or services into their applications.
A web API is an API accessible through web technologies (HTTP or HTTPS). They often
use JSON as their data format.
A web API can be consumed programmatically using an AJAX call. Before that, the API
must be checked out and its documentation studied in order to understand how it works
and what it returns.
A ever growing number of services are exposed through web APIs. Some are open, others
require the authentication of the client, for example with an access key.
A web API is an API available on the Web and accessible through web technologies, namely the
HTTP protocol or its secured counterpart HTTPS. Web APIs are a key technology for software
interactions: whenever you authenticate into a website using your Google account, or click a
button to post something on your favorite social network, youre using them. A ever growing
number of services are exposed through web APIs, forming a thriving ecosystem for building
digital products.
This raw result is not easy to read. For an easier interaction with web API, using a specialized
tool like Postman1 or RESTClient2 is strongly recommended. Heres how the result looks like on
Postman.
1
https://www.getpostman.com
2
https://addons.mozilla.org/fr/firefox/addon/restclient/
Use web APIs 212
This web API returns an array containing some articles. Each article corresponds to a JavaScript
object with id, title and content properties.
Curious about creating such an API? Youll learn how to build this very service (and
others) in an upcoming chapter.
Real-world APIs are almost always accompanied by an online documentation showing how to
use it. Studying this documentation is essential for using the API flawlessly.
Using a web API works just like querying a web server: fetching the API URL, translating the
JSON response into a JavaScript array and iterating on it.
Here is the resulting web content.
Execution result
Use web APIs 214
Open APIs
These APIs are free to use by anyone, anyhow. To prevent abuse, they often use rate limiting
instead: the number of calls from one specific source (identified by its IP address) is capped.
Many public institutions like the British Police3 or the French government4 publish data to
citizens using open APIs.
There is also a lot of fun little APIs out there. For example, the Punk API5 lets you search into a
huge catalog of beers. Heres how to renew your drinking habits by getting a random one from
this API.
})
.catch(err => {
console.error(err.message);
});
};
Each time the "Grab a beer" button is clicked on the web page, an anonymous function is called
to retrieve and display a random beer.
Execution result
Key-based authentication
Another class of APIs requires the client to authenticate himself when accessing the service.
Authentication can be done via several techniques. In this paragraph, well use the simplest one:
access key. An access key is a generated string containing characters and digits and associated
to a user.
There is no universal standard regarding access keys. Each service is free to use its own custom
format. The client must provide its access key when accessing the API, generally by adding it at
the end of the API URL.
A prerequisite for using any key-based web API is to generate oneself an access key for this
particular service.
Lets put this into practice for obtaining about the current weather in your area. To do so, you
could simply look outside the window, but its way cooler to use the Weather Underground6 web
service instead.
6
https://www.wunderground.com/weather/api
Use web APIs 216
This service has a key-based API for retrieving the weather in any place. To obtain it, youll have
to sign up as a user (its free) and generate a new API key by registering your application.
Once youve done this, weather data is available through an URL of the form http://api.
wunderground.com/api/ACCESS_KEY/conditions/q/COUNTRY/TOWN.json. Replace ACCESS_-
KEY, COUNTRY and TOWN with your own settings, and you should obtain the weather in your
surroundings.
The necessary first step is to check out and understand the API data format. The result of an API
call looks like this when getting weather for Bordeaux, France.
{
"response": {
"version": "0.1",
"termsofService": "http://www.wunderground.com/weather/api/d/terms.html",
"features": {
"conditions": 1
}
},
"current_observation": {
"image": {
"url": "http://icons.wxug.com/graphics/wu2/logo_130x80.png",
"title": "Weather Underground",
"link": "http://www.wunderground.com"
},
"display_location": {
"full": "Bordeaux, France",
"city": "Bordeaux",
"state": "33",
...
},
"observation_location": {
"full": "Bordeaux, ",
"city": "Bordeaux",
"state": "",
"country": "FR",
...
},
"estimated": {},
"station_id": "LFBD",
"observation_time": "Last Updated on June 28, 9:30 PM CEST",
...
}
}
Now we just have to call the API from our JavaScript code and displays the main result on a web
page.
Use web APIs 217
fetch(
"http://api.wunderground.com/api/YOUR_OWN_KEY/conditions/q/france/bordeaux.\
json"
)
.then(response => response.json())
.then(weather => {
// Access some weather properties
const location = weather.current_observation.display_location.full;
const temperature = weather.current_observation.temp_c;
const humidity = weather.current_observation.relative_humidity;
const imageUrl = weather.current_observation.icon_url;
// Create DOM elements for properties
const summaryElement = document.createElement("div");
summaryElement.textContent = `Temperature is ${temperature} C with ${hum\
idity} humidity.`;
const imageElement = document.createElement("img");
imageElement.src = imageUrl;
// Add location to title
document.querySelector("h2").textContent += ` ${location}`;
// Add elements to the page
const weatherElement = document.getElementById("weather");
weatherElement.appendChild(summaryElement);
weatherElement.appendChild(imageElement);
})
.catch(err => {
console.error(err.message);
});
Coding time!
Expected result
GitHub profile
The ubiquitous code sharing platform GitHub7 has a public API. The goal of this exercise is to
display some information about a GitHub user, identified by his login. The API documentation
is available here8 .
Use this API to show the profile picture, name and website address of a GitHub user whose login
is entered in a text box.
7
https://github.com
8
https://developer.github.com/v3/users/
Use web APIs 219
Expected result
You can test your code by using the GitHub logins of prominent JS community
members like brendaneich (JavaScripts father), douglascrockford or vjeux.
Write the associated JavaScript code so that a list of links for the first ten planets identifiers (from
1 to 10) is generated automatically. Clicking on a planet link shows information about it.
9
https://swapi.co/
Use web APIs 220
Expected result
23. Send data to a web server
You know now how to retrieve some data from web servers or APIs. This chapter will teach you
how to send data to them.
TL;DR
You can send information to a web server through an AJAX call translating into an HTTP
POST request using the fetch() method.
For sending HTML form data or key/value pairs, you use the FormData object.
The FormData object can also be used to send arbitrary key/value pairs to a server.
When the information expected by the server is more structured, sending it as JSON data
is more convenient.
Send data to a web server 222
Form display
And here is the associated JavaScript code which handles the form submission.
});
});
The event listener starts by disabling the default form submission behavior, which is to send
a synchronous HTTP POST request to a server. Instead, a FormData object is created with the
form itself (the e.target expression) as a parameter. All form fields are automatically added as
key/value pairs in this object.
Once the form fields are encapsulated in the FormData object, the fetch() method seen previ-
ously is used to send an asynchronous request to the https://thejsway-server.herokuapp.com/animals
URL. The second parameter of the fetch() call sets the HTTP method as POST and adds the form
data into the body of the request.
Lastly, the pages result element is updated when the server responds to the asynchronous
request.
Submission result
The FormData object can also be used independently of any form, to send custom key/value pairs
to a server. Here is a very basic example form containing only a button.
When the user clicks on the button, custom data is added to a FormData object and sent to the
server through an asynchronous POST request.
Send data to a web server 225
Submission result
}
];
Execution result
The second parameter of the fetch() call sets POST as the HTTP method to use, updates the
request headers to indicate that the data format is JSON, and adds the JSON representation of
the JavaScript array into the body of the request.
Coding time!
New article
Write the HTML code that shows input fields for creating a new blog article by entering its title
and content.
Then, write the associated JavaScript code to send the article fields as form data to the
URL https://thejsway-server.herokuapp.com/articles. You should receive a confirmation
message from the server and display it on the page.
Send data to a web server 227
Execution result
Visited countries
The goal of this exercise is to send your traveling info to a server. Data is expected as a JSON
object containing two fields:
Execution result
24. Discover Node.js
In this chapter, youll discover how to create JavaScript applications outside the browser thanks
to a technology called Node.js.
TL;DR
Node.js (or simply Node) is a platform built on Chromes JavaScript engine (V8) to create
JavaScript applications outside the browser.
Node emphasizes modularity: instead of being monolithic, applications are designed as a
set of small, focused modules working together to achieve the desired behavior.
Node adheres to the CommonJS1 module format. It provides a require() for loading a
module.
Inside a module, the module.exports object is used to export pieces of code. You can add
properties to it to export element. You can also reassign module.exports to export only
a specific element.
Node provides a way to structure an application under the form of a package. A package
is a folder containing an application described by a package.json file. The default entry
point of a package is the index.js file.
Package versions are defined using the semantic versioning format: a three-digit string
of the form MAJOR.MINOR.PATCH. This format facilitates the management of dependencies
between packages.
npm2 (Node Package Manager) is the standard package manager for the Node ecosystem.
It consists of a command line client and an online registry of public packages accessed by
the client. This registry is the largest ecosystem of open source libraries in the world.
The main npm commands are npm install (to install all the dependencies of a package
or adding a new one) and npm update (to update all the packages and install missing ones
according to package.json).
Once installed through npm, packages defined as dependencies are stored in the node_-
modules/ subfolder and can be loaded as modules using require().
Some packages (containing only executable files or no entry point) cannot be loaded as
modules. Some modules (single JavaScript files) are not packages.
1
http://requirejs.org/docs/commonjs.html
2
https://www.npmjs.com
Discover Node.js 229
Introducing Node.js
A bit of history
To understand what Node.js3 (or Node for short) is, we have to travel back in time to the 2000s.
As JavaScript was becoming increasingly important for improving the user experience on the
web, web browser designers spent a considerable amount of resources on executing JS code as
fast as possible. In particular, the Chrome JavaScript engine, codenamed V8, became open source
in 2008 and was a huge step forward in general performance and optimization.
Chrome V8 logo
The core idea behind Node.js was simple yet visionary: since the V8 engine is so good at executing
code, why not leverage its power to create efficient JavaScript applications outside the browser?
And thus Node.js was born in 2009, originally written by Ryan Dahl. Its project quickly became
very popular and Node is now one of the top technologies for building apps and creating APIs
with JavaScript.
3
https://nodejs.org
Discover Node.js 230
Node also made it easier for developers to publish, share and reuse code. Today, hundreds
of thousands of ready-to-use JavaScript libraries, called packages, are available and easy to
integrate in any Node-based project (more on that later). This rich ecosystem is one of Nodes
greatest strengths.
A first example
The rest of this chapter assumes a working Node environnement. Refer to the
appendix for setting one up.
As you see, the console.log() command is also available in Node. Just like in a web browser,
it outputs the value passed as parameter to the console. Assuming this code is saved into a file
named hello.js, heres how to execute it through Node in a terminal.
node hello.js
Discover Node.js 231
Execution result
An in-depth study of the Node platform is out of this books scope. Lets focus on two of its
defining features: modules and packages.
Node.js modules
Creating a module
The simplest form of module is a single JavaScript file, containing special commands to export
specific pieces of code. The rest of the code is private to the module and wont be visible outside
of it.
For example, a greetings.js module could contain the following code.
4
http://requirejs.org/docs/commonjs.html
Discover Node.js 232
In Node, functions can be exported (made accessible outside) by specifying additional properties
on the special module.exports object. Here, two functions are exported under the names
sayHello and flatter. The third one is not exported.
This module could have been written in a slightly more concise way by directly defining the
functions as properties of the module.exports object.
Loading a module
Assuming both files are located in the same directory, another JavaScript file could load the
previously created module by using the require() function provided by Node.js.
The parameter passed to require() identifies the module to load. Here, the "./" substring at the
beginning indicates a relative path: the module should be searched for in the same directory as
the file that loads it.
The result of the call to require() is an object, named greetings here. This object references the
value of the module.exports object defined inside the module. Thus, the greetings object has
two functions sayHello and flatter as properties. Trying to access its non-existent sayGoodbye
property triggers an error during execution.
Giving the object resulting from a call to require() the same name as the loaded
modules name, through not mandatory, is a common practice.
Discover Node.js 233
In this module, the only exported element is a function that returns an object literal. Using it in
another file (located in the same folder) is as follows.
The result of the call to require() is a function stored in the calculator variable, referencing
the createCalc() function. Calling this function returns an object with several methods, which
can be subsequently used.
Discover Node.js 234
Heres how to use this class in another file (located in the same folder).
Execution result
Node.js packages
The Node platform provides a way to structure an application under the form of a package.
Anatomy of a package
Technically, a package is a folder containing the following elements:
name (all lowercase letters without dots, underscores and any non-URL safe character in
it).
version (following the semantic versioning format - more on that later).
{
"name": "thejsway-node-example",
"version": "1.0.0",
"description": "Node example for the book \"The JavaScript Way\"",
"scripts": {
"start": "node index.js"
},
"dependencies": {
"moment": "^2.18.1",
"semver": "^5.3.0"
},
"keywords": [
"javascript",
"node",
"thejsway"
],
"author": "Baptiste Pesquet"
}
Semantic versioning
Node packages are versioned using a format called semantic versioning. A version number is
a three-digit string of the form MAJOR.MINOR.PATCH (example : 2.18.1).
Here are the rules for defining a version number:
These strict rules exist to facilitate the management of dependencies between packages.
Dependencies
In the package.json file definition, the dependencies field is used to declared the external
packages needed by the current package. Each dependency is created with the package name
followed by a version range. This version range specifies the package versions that are
acceptable to use.
There are many ways to define a version range. The most commonly used ones are:
Using the ^ operator to allow changes that do not modify the left-most non-zero digit in
the version. Examples:
The ^2.18.1 version range accepts versions 2.18.7 and 2.19.0, but not 3.0.0.
The ^0.2.3 version range accepts version 0.2.5 but not 0.3.0 nor 1.0.0.
Fine-tuning the targeted versions of external packages though version ranges helps limiting the
risk of breaking the application apart when updating its dependencies.
npm logo
Over 477,000 packages are now available on the registry, ready to reuse and covering various
needs. This makes npm the largest ecosystem of open source libraries in the world.
The npm client is used by typing commands in a terminal open in the packages folder. It offers
numerous possibilities for managing packages. Lets study two of the most important ones.
Installing dependencies
To install all the dependencies of a package, you type the following npm command.
npm install
This will read the package.json file, look for the packages satisfying the version ranges declared
in the dependencies field, and download and install them (and their own dependencies) in the
node_modules/ subfolder.
npm update
This will update all the packages listed to the latest version respecting their version range, and
install missing packages.
The other way is to run the following command.
This command will fetch a specific package from the registry, download it in the node/modules/
subfolder and (since npm 5) update the package.json file to add it as a new dependency. The
<package-id> parameter is usually the dependencys package name.
Using a dependency
Once external packages have been installed in node_modules/, the application can load them as
modules with the require() function.
For example, the npm registry has a semver package that handles semantic versioning. Assuming
this package has been installed as a dependency, it can be used to perform manual version range
checks.
A package used in another Node application is loaded with require(), making it a module. To
be loaded as a module, a package must contain an index.js file or a main field in package.json
defining a specific entry point.
Some packages only contain an executable command and thus cannot be loaded as modules. On
the other hand, a single JavaScript file loaded with require() is a module but not a package,
since it doesnt have a package.json file.
Check out the npm documentation7 for more details on this aspect.
7
https://docs.npmjs.com/how-npm-works/packages
Discover Node.js 239
Coding time!
Circles again
Create a circle.js module exporting two functions circumference() and area(), each taking
the circle radius as a parameter.
Load this module in a index.js file and test the two functions.
Execution result
Accounting
Create a accounting.js module exporting.
Load this module in a index.js file and test the two functions.
Execution result
Execution result
9
https://momentjs.com/docs/
25. Create a web server
Its time to put your Node.js knowledge into practice and create a real-world web server in
JavaScript. This is often called back-end programming.
You will build exactly the server that was used in the previous chapters dealing
with client-side web development. To test your server code, you can go back to
code examples from chapters 22 and 23, and only change the start of the server URL
from https://thejsway-server.herokuapp.com to your own server URL (which
would be http://localhost:3000 if your server runs on your local machine).
TL;DR
The Node.js platform is well suited for creating web servers in JavaScript, with or without
the help of a framework.
A framework provides a standard way to design and structure an application. Express is
a common choice for building a web server with Node.
In order to respond to requests, an Express app defines routes (entry points associated to
URLs) and listens to incoming HTTP requests.
The main Express method are get() to handle a GET request, post() to handle a POST
request and use() to define a middleware (code that runs during the request/response
cycle).
Incoming form or JSON data can be managed through specialized packages like multer
and body-parser.
JavaScript can be used on both the client side (browser) and the server side of a web
application. This empowers you to create complete web applications.
Using a framework
We saw in the previous chapter that Node.js is a platform for building JavaScript applications
outside the browser. as such, Node is well suited for creating web servers in JavaScript.
About frameworks
Its entirely possible to build a web server from scratch with Node, but well take a different
approach and use a framework for it.
In computer programming, a framework provides a standard way to design and structure an
application. It typically takes care of many low-level details so that the developer can concentrate
on high-level, business-related tasks.
Create a web server 243
Choosing a framework
Among the many possible frameworks for creating a web server in JavaScript, well use one of
the most well-known: Express. To paraphrase its web site1 , Express is a minimal and flexible
Node.js web application framework that provides a robust set of features for web and mobile
applications.
In other words, Express provides a foundation on which you can easily and quickly build a web
server.
Installing Express
The Express framework is available as an npm package and its installation is straightforward.
First, youll need an existing Node application with a package.json file it. Run the following
command in a terminal open in your application folder to install Express as a dependency.
As an alternative, you can directly add Express as a dependency in your package.json file and
run the npm install command.
"dependencies": {
"express": "^4.15.3"
},
Responding to requests
The main job of a web server is to respond to HTTP requests. Heres the JavaScript code for a
minimal Express-based web server that returns "Hello from Express!" for a request to the root
URL.
You can launch your server with either node index.js or npm start, then type its root URL
(http://localhost:3000 if your server runs on your local machine) in a browser. You should see the
string "Hello from Express!" appear.
Execution result
Defining routes
In web development terminology, a route is an entry point into an application. It is relative to
the application URL. The "/" route matches the root of the application.
When an HTTP request is made to the route URL, the associated callback function is executed.
This function takes as parameters objects representing the HTTP request and response. Here, the
function body sends a text response with the content "Hello from Express!".
Listening to requests
To process incoming request, a web server must listen on a specific port. A port is a communi-
cation endpoint on a machine.
The main Express object has a listen() method that tasks as parameter the listening port and
a callback function called for each request. The last part of the server code calls this method to
start listening.
Creating an API
Your web server is pretty limited for now, handling only one route and always returning the
same string. Lets create your own little API by publishing some data in JSON format.
This is an example of a middleware: code that runs somewhere between the reception of the
HTTP request and the sending of the HTTP response.
Exposing data
To match what was done on the client side in a previous chapter, well publish some blog articles.
The API route is "/api/articles", and the associated callback return a list of JavaScript objects.
Heres the code to be added to the server just before the last part (the one that starts the listening).
Execution result
Accepting data
So far, your web server offers a read-only service: it publishes some data but doesnt accept any
Until now!
As you saw in a previous chapter, information submitted to a web server can be either form data
or JSON data.
"dependencies": {
...
"multer": "^1.3.0"
},
Once multer is installed, add the following code towards the beginning of your server main file.
2
https://www.npmjs.com/package/multer
Create a web server 248
The following route accepts form data sent to the "/animals" route. Notice the use of app.post()
instead of app.get() to handle POST HTTP requests, and the addition of upload.array() as a
second parameter to add a body object containing the fields of the form to the request object.
The values of the name and vote variables are extracted from the request body, and a string is
constructed and sent back to the client.
Execution result
3
https://www.npmjs.com/package/body-parser
Create a web server 249
"dependencies": {
...
"body-parser": "^1.17.2"
},
Then, add the following code towards the beginning of your server main file.
The following code handle POST requests to the "/api/cars" route. JSON data is parsed by
jsonParser and defined as the request body.
Execution result
However, things would quickly get out of hands as the complexity of the web page grows. A
better solution is to define the HTML content in an external file stored in a dedicated subfolder,
and return that file as a result of the request.
For example, create a subfolder named views and a file named hello.html inside it. Give the
HTML file the following content.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Hello web page</title>
</head>
<body>
<h2>Hello web page</h2>
<div id="content">Hello!</div>
</body>
</html>
Then, update the callback for the "/hello" route to send the HTML file as the request response.
Pointing your browser to the "/hello" URL (http://localhost:3000/hello if your server runs
locally) should now display the web page.
Create a web server 251
Execution result
Most web pages will need to load client-side resources such as images, CSS and JavaScript files.
A common practice is to put these assets in a dedicated subfolder.
For example, create a public subfolder and a hello.js JavaScript file inside it with the following
content.
You should now have the following folder structure for your server.
Folder structure
<script src="/hello.js"></script>
Lastly, you must tell Express that client assets are located in the public subfolder, so that the
server can serve them directly. Add the following code towards the beginning of your main
application file.
Accessing the "/hello" URL shows you a slightly different result. The hello.js file was loaded
and executed by the browser, updating the web page content.
Execution result
In this example, JavaScript was used both for back-end (server side) and front-end (client
side) programming. This is one of its core strengths: knowing only one programming language
empowers you to create complete web applications. How great is that?
Coding time!
T-shirt color
Add a "/tshirt" route to your server for handling the submission of form data containing a size
and a color field, like in the chapter 23 example. In the route callback, send back a confirmation
message to the client.
Create a web server 253
Execution result
Visited countries
Add a "/api/countries" route to your server to manager traveler information received as JSON
data, like in the chapter 23 exercise. In the route callback, send back a confirmation message to
the client.
Execution result
New article
Add a "/articles" route to your server. This route should accept a new blog article as form data
and add it to the servers article list, like in the chapter 23 exercise. The new article ID must be
equal to the maximum ID among existing articles plus one.
Create a web server 254
Execution result
Conclusion
Summary and perspectives
Congratulations, you made it to the end!
TL;DR
This book covers a lot of ground. Here are some key takeaways.
All the resources listed here are freely available online, although some of them
require registration or are also sold in another format. They were picked for their
relevance, without any affiliation.
Summary and perspectives 257
Keep on practicing
This is by far the most important advice. Nothing will sharpen your skills and make you more
confident as a JavaScript developer than practicing your craft on a regular basis.
In particular, I urge you to start building a personal project right now. This is the best solution
to stay focused and create something meaningful while having fun along the way.
You may already have a project idea in the back of your mind. If not, here are a few things you
could build:
Still undecided or looking for more? Take Wes Bos JavaScript305 coding challenge and build 30
things in 30 days. Yes you can!
Kyle Simpsons You Dont Know JS6 , a book series diving deep into the core mechanisms
of the language.
Axel Rauschmayers authoritative blog7 and books8 .
Ilya Kantors javascript.info9 , an online tutorial with a lot of interesting content.
The JavaScript section of the Mozilla Developer Network10 , full of reference material,
guides and tutorials.
Lastly, you might want to check out my own little curated collection11 of JavaScript-related links.
4
https://en.wikipedia.org/wiki/Connect_Four
5
https://javascript30.com/
6
https://github.com/getify/You-Dont-Know-JS
7
http://2ality.com/
8
http://exploringjs.com
9
http://javascript.info
10
https://developer.mozilla.org/fr/docs/Web/JavaScript
11
http://www.pearltrees.com/t/javascript/id13385349#l634
Summary and perspectives 258
Get social
JavaScripts popularity is peaking. Why not becoming a part of its huge developer community?
Thanks to code sharing platforms like GitHub12 , you can easily look for examples of code, see
how other developers work and even get involved in a project. Thats the beauty of open source!
When facing a problem, knowing how to find the best answers is a critical skill. Stack Overflow13
is your best bet for asking questions and sharing knowledge with tons or other developers.
Lastly, you could join a learning community in order to share experiences (good or bad) and build
relationships. There are JavaScript user groups in many cities of the world, look for one in your
neighborhood. Should you prefer socializing online, Quincy Larsons freeCodeCamp14 features
a broad curriculum including many projects and a helpful, beginner-friendly community.
Whichever road you may take, I wish you a great journey into the wonderful world of JavaScript!
12
https://github.com
13
https://stackoverflow.com/
14
https://www.freecodecamp.org
Acknowledgments
This book was built upon two online courses I wrote for the French EdTech startup OpenClass-
rooms15 :
Thanks to Jessica Mautref20 for her watchful eye during the writing process, and to Emily Reese21
for the initial English translation. Both also contributed many good ideas.
Ive been inspired by other authors who decided to publish their books in an open way: Kyle
Simpson22 , Nicholas C. Zakas23 , Axel Rauschmayer24 and Marijn Haverbeke25 .
Thanks to everyone who improved the book content through contributions. In chronological
order: Gilad Penn, NewMountain, Emre Akbudak, opheron, Theo Armour, Filip Biaek, Keely-
Bird, Juhani Niinimaa, Louis Rainier, Chandan Rai, ScottyRotten, SrZorro, Frank Paulo Filho,
Ryan Lindsey, Michael Dilger, Ramil Muratov, Ganesh Kumar Kattamuri, Samuel Fuller Thomas,
Florian Loch, Daniel Sorichetti, Jake Ingman, John Hassell, Conrad Knapp, Ahmed Shamim,
Vse Mozhet Byt, AGCB, William Friesen, Robert Morrison, Derek Houck, Zac Walberer, Tom
Paoletti, Luk Bacigl, Annie Baraban, alee156, Ahmed Zeeshan, Matthew Loseke, M Afiq,
Justin Crabtree, Marco Dahms, Miguel T Rivera.
Illustration credits:
15
https://openclassrooms.com
16
https://openclassrooms.com/courses/learn-the-basics-of-javascript
17
https://openclassrooms.com/courses/apprenez-a-coder-avec-javascript
18
https://openclassrooms.com/courses/use-javascript-on-the-web
19
https://openclassrooms.com/courses/creez-des-pages-web-interactives-avec-javascript
20
https://www.linkedin.com/in/jessicamautref
21
https://www.linkedin.com/in/eclairereese
22
https://github.com/getify
23
https://www.nczonline.net/
24
http://dr-axel.de/
25
http://marijnhaverbeke.nl/
26
http://www.logoopenstock.com/logo/preview/64186/creative-blue-swirl-logo-design
27
http://www.free-logodesign.com/
28
https://segment.com/blog/the-deep-roots-of-js-fatigue/
Appendices
Environment setup
Prerequisite: a modern browser
This book targets a recent version of the JavaScript language. More specifically, youll need a
browser able to run code written in the ES2015 (ES6) language specification.
A browser is the software you use to visit webpages and use web applications. Check what-
browser.org29 for more info and advice about upgrading your browser, and this compatibility
table30 for more detail about ES2015 support among browsers.
The safest bet is to choose either Google Chrome or Mozilla Firefox, two evergreen (self-
updated) browsers with excellent ES2015 support in their recent versions. Other capable browsers
include Opera and Microsoft Edge (Windows 10s default browser). On the contrary, all versions
of Internet Explorer will have issues with ES2015 code: stay away from them.
If you choose to use CodePen, you really should start by visiting Welcome to CodePen34 . 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 autocomplete35 ,
the console36 , pen autosaving37 , keybindings38 and auto-updating39 . 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 and project youll search.
For performance reasons, the CodePen console does not always show the same
amount of information as the real browser console.
You can learn more about Glitch here41 and start by remixing this project42 .
The easiest way to test that node is installed is to run the node --version command in your
terminal/command prompt, and check that a version string is returned.
node --version
A code formatter frees you from the burden of formatting your code manually and
improves consistency. Prettier48 is the current standard.
A linter can greatly improve your codes quality, detecting bugs and enforcing good
practices. ESLint49 is a common choice.
The easiest way to setup ESLint and Prettier is to add them as extensions (sometimes named
add-ons) to your code editor. For VS Code, use these links:
Prettier extension50 .
ESLint extension51 .
For chapters 1 to 23
In these chapters, youll execute your JavaScript code in the browser. Your files will be stored
according to their type: HTML files (the ones with an .html extension) in an html subfolder, CSS
files (.css) in a css subfolder and JavaScript files (.js) in a js subfolder. Each chapter is set up
in a series of folders as follows.
For examples and each exercise of a chapter, create an HTML file in the html subfolder of the
chapter folder. In these HTML files, a <script> will load the associated JavaScript code.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Code examples</title>
</head>
<body>
<!-- HTML code goes here -->
<script src="../js/examples.js"></script>
</body>
</html>
This <script> tag asks the browser to load the examples.js JavaScript file, located at path
../js/examples.js. The two dots (..) at the beginning of the path indicate youre going back
one level in the directory structure relative to the HTML file itself before looking in the js
subfolder for a file named examples.js.
Next, open the HTML file in your browser to execute the JavaScript code stored in the .js file.
Its result will be shown in the browser console (see below).
In these chapters, youll create Node.js applications to execute your JavaScript code. Each Node
app must sit in its own folder and is described by a package.json file located at the root of this
Environment setup 266
Check out the following links to discover more about browser developer tools:
53
https://www.khanacademy.org/computing/computer-programming/html-css/web-development-tools/a/using-the-browser-developer-
tools
54
https://openclassrooms.com/courses/optimize-your-website-with-devtools
55
https://developer.chrome.com/devtools
56
https://developer.mozilla.org/en-US/docs/Tools
Style guide
Here are the coding rules and principles used throughout the book.
This chapter is by nature subjective and opinionated. Feel free to make your own
choices.
Naming
Naming things right goes a long way into making code cleaner and easier to understand. Some
general naming rules are presented below.
To be consistent with other programming languages, class names start with an uppercase
letter: User instead of user.
Since they may contain multiple elements, arrays are named plurally or suffixed with
List: movies or movieList, but not movie.
To distinguish them from other variables, DOM elements are suffixed with Element (or
Elements for array-like variables): divElement rather than simply div.
Like many other languages, JavaScript is case sensitive. For example, myVariable and
myvariable are two different variable names. Be careful!
Code formatting
This is a subject of many debates in the JavaScript community: using spaces or tabulations for
indenting, omitting semicolons, simple vs double quotes for strings, and so on.
A simple and efficient solution is to rely on a tool to automate the low-level task of formatting
code, so that you can concentrate on more high-level work. This book uses Prettier59 with default
configuration (double quotes and semicolons).
Code quality
Since JavaScript is a dynamically typed language, a number of errors dont show up until
execution: misnaming a function, loading a nonexistent module, etc. In addition, many other
mistakes like declaring a variable without ever using it wont affect execution outcome, but
make your code harder to read and lower its overall quality.
Fortunately, specialized tools called linters can check your code against rules during edition and
warn about potential defects. By allowing to fix many bugs before they happen, linters greatly
enhance developer productivity.
This book uses ESLint60 for linting code. ESLint is a very flexible tool and you can tailor it to
your specific needs. Different set of ESLint rules have emerged, notably one based on the popular
AirBnb Style Guide61 .
This books ESLint configuration extends the AirBnb and Prettier rules (Prettier getting the
precedence), with a few minor deviations.
Here is the content of the books .eslintrc configuration file.
59
https://github.com/prettier/prettier
60
http://eslint.org
61
https://github.com/airbnb/javascript
Style guide 269
{
"extends": ["airbnb", "prettier"],
"env": {
"browser": true
},
"plugins": ["prettier"],
"rules": {
"no-console": "off",
"no-alert": "off",
"no-plusplus": "off",
"default-case": "off",
"no-param-reassign": [
"error",
{
"props": false
}
],
"arrow-body-style": [
"error",
"as-needed",
{ "requireReturnForObjectLiteral": true }
]
}
}