The JavaScript Workbook - Download Edition
The JavaScript Workbook - Download Edition
PT
DEVE
LOPME
NT
WO
RKB
OOK
T
he
Pr
ov
en
,A
ct
i
ve
Way
to
Le
ar
nJ
AV
AS
CR
I
PT
M
AR
KL
AS
SO
FF
The JavaScript
Development Workbook
A Practice-Based Approach to Learning
JavaScript Fundamentals
The JavaScript Development Workbook
A Practice-Based Approach to Learning JavaScript
Fundamentals
Mark Lassoff
ISBN: 9798393425623
©2023
© 2023 LearnToProgram.tv, LLC d/b/a Framework Tech Media.
All rights reserved. No part of this book may be reproduced or
transmitted in any form or by any means, electronic or
mechanical, including photocopying, recording or by any
information storage and retrieval system, without written
permission from the author, except for the inclusion of brief
quotations in a review.
Note that this notice informs readers that all rights are
reserved and prohibits the reproduction or transmission of any
part of the book without written permission from the author. It
also allows for the inclusion of brief quotations in a review, in
accordance with fair use laws.
For Mom and Rick. Thank you for everything.
Detailed Table of Contents
Introduction 13
Section 1: JavaScript Quick Start 15
Introduction 15
Setting up your development environment 15
Choosing a Text Editor 16
Creating an HTML File 17
Creating a JavaScript File 17
Linking JavaScript to HTML 18
Running Your Code 18
More On Running JavaScript Code 18
Using the Browser Console 18
Using an HTML File 19
Using a Code Editor 20
Best Practices for Testing Your Code 20
Basic JavaScript Concepts and Syntax 20
Console.log 21
Variables 23
Data Types 23
Operators 25
Arithmetic Operators 25
Comparison Operators 25
Logical Operators 25
Functions 26
Code Exercises 26
Section 2: Variables and Data Types 29
Introduction 29
Declaring Variables 30
Variable Types 30
Let vs. Const 31
Best Practices 32
Primitive Data Types 32
Strings 32
Numbers 33
Booleans 34
Null 34
Undefined 34
Complex Data Types 35
Arrays 35
Objects 36
Functions 37
Type Coercion and Conversion 37
Type Coercion 38
Type Conversion 38
Loose vs Strict Equality 39
Critical Points 40
The FAQ 41
Code Exercises 42
Section 3: Control Flow and Loops 44
Introduction 44
Conditional Statements 44
If/Else Statements 45
Switch/Case Statements 46
The prompt() Function 47
Code Exercises 47
Iteration Statements (for, while, do/while) 48
The for Loop 48
The while Loop 49
The do/while Loop 49
Choosing the Right Loop 50
Code Exercises 51
Loop control statements (break, continue) 52
The break statement 52
The continue statement 53
Combining break and continue 53
Coding Exercises 54
Critical Points 55
The FAQ 56
Section 4: JavaScript Functions 57
Introduction 57
Declaring and Calling Functions 57
Declaring Functions 58
Calling Functions 58
Function Return Values 59
Function Parameters and Arguments 59
Defining Function Parameters 60
Using Function Arguments 60
Default Parameter Values 61
Rest Parameters 61
Code Exercises 62
Function expressions and arrow functions 63
Function Expressions 63
Arrow Functions 63
Code Exercise 64
Function Scope and Closures 65
Function Scope 65
Global Scope 66
Closures 67
Code Exercises 68
Critical Points 68
The FAQ 70
Section 5: Working with Arrays 72
Declaring and initializing arrays 72
Declaring Arrays 72
Initializing Arrays 73
Accessing Array Members 74
Addressing Non-Existent Array Members 74
Multidimensional Arrays 75
Array methods (push, pop, shift, unshift, etc.) 76
Adding Elements with push() and unshift() 76
Removing Elements with pop() and shift() 77
Modifying Elements in an Array with splice() 77
Finding Elements in an Array with indexOf() 77
Checking If an Array Includes an Element with
includes() 78
The slice() method 78
The splice() method 78
The concat() method 79
Converting Arrays to Strings and Vice Versa 79
The join() method 79
The split() method 80
Iterating Through Arrays with For and While Loops 81
Iterating Through Arrays with a For Loop 81
Iterating Through Arrays with a While Loop 82
Iterating over arrays (forEach, map, filter, reduce) 83
forEach() 83
map() 84
filter() 85
Code Exercises 86
Critical Points 88
The FAQ 90
Section 6: Objects in JavaScript 92
Built-in JavaScript Objects Versus Custom Objects 92
Built-In Objects 92
Custom Objects 93
Properties and Methods 93
Prototypes and Inheritance 93
Objects, Instances, Properties and: A Metaphor 94
Creating Objects: Object literals and constructors 95
Object Literals 95
Constructors 96
Comparing Object Literals and Constructors 97
Properties and methods 97
Accessing Properties 97
Modifying Properties 98
Methods 98
Prototypes and inheritance 99
Introduction to Prototypes 99
Creating a Prototype Object 100
Creating an Object with a Prototype 100
Inheritance and the Prototype Chain 100
Overriding Properties and Methods 101
Classes and Objects in the Real World: Vehicles 101
Creating the Vehicle Class 101
Inheriting Properties and Methods 102
Using the Classes 104
Creating an Ambulance 104
Creating a Bus 104
Using the Methods 105
Inheritance in Action 105
Code Exercises 106
Critical Points 107
The FAQ 108
Section 7: Error Handling 110
Types of errors (syntax, runtime, logic) 110
Syntax Errors 110
Runtime Errors 111
Logic Errors 111
Using Developer Tools in Your Browser 112
Reviewing the Console 112
Tracing Variables 112
Inserting Breakpoints 113
Code Exercise 113
try/catch/finally statements 116
The try Block 116
The catch Block 116
The finally Block 117
Putting it All Together 117
Code Exercise 118
Throwing and catching exceptions 119
The throw statement 119
The try and catch statements 120
The finally statement 120
Code Exercise 121
Critical Points 122
The FAQ 123
Section 8: DOM Manipulation 125
The Document Object Model (DOM) 125
DOM Tree Structure 126
Accessing DOM elements 126
getElementById() 126
querySelector() 126
querySelectorAll() 127
Elements by Tag Name or Class Name 127
Dom Manipulation: In Action 127
Modifying DOM Elements 129
Modifying Text Content 129
Modifying HTML Content 130
Modifying Attributes 131
Modifying CSS 132
Modifying inline styles 132
Modifying classes 133
Responding to events 135
Event Listeners 135
Event Handling 135
Event Propagation 136
The Event Object 136
The Event Object Applied 138
Code Exercises 139
Critical Points 143
The FAQ 145
Section 9: Asynchronous JavaScript 147
Callback functions 147
Passing Functions as Arguments 148
Nested Callbacks 148
Promises 150
Introduction to Promises 150
Creating a Promise 150
Consuming a Promise 151
Chaining Promises 151
Error Handling with Promises 152
Async/await 153
What is Async/Await? 153
Async Functions 153
Error Handling 154
Using Async/Await with Promise.all 155
Using the Fetch API for HTTP requests 155
Sending a GET Request with Fetch 156
Handling Errors with Fetch 156
Using Async/Await with Fetch 157
Parsing XML data from APIs 158
Parsing JSON Data Returned from an API 160
Code Exercise 161
Critical Points 162
The FAQ 163
Section 10: JavaScript Tools and Libraries 164
Node.js and npm 165
Installing Node.js and NPM 166
Creating a Node.js Project 166
Using Third-Party Packages 166
Webpack and Babel 167
Installing Webpack and Babel 168
Configuring Webpack and Babel 168
React and other front-end frameworks 169
Introduction to React 169
Creating a React Component 169
Rendering a Component 170
Handling Events 171
Express and other back-end frameworks 172
Installing Express 172
Creating an Express Server 172
Handling Requests and Responses 173
Using Other Back-end Frameworks 174
Testing frameworks (Jest, Mocha, etc.) 174
Writing Tests with Jest 174
Writing Tests with Mocha 175
Code Coverage 176
Critical Points 177
The FAQ 178
Section 11: JavaScript Projects 180
Project: Weather App 180
Project: To Do List 181
Project: Calculator 181
Project: Random Quote Generator 182
Project: Memory Game 182
Project: Hangman 183
Project: Recipe App 183
Project: BART Transit Tracker 184
Project: Explore Your City 184
Excerise Soutions 186
Introduction
Hi there! I'm excited to introduce you to my book, "The
JavaScript Development Workbook." This book is all about
learning JavaScript through practical coding exercises and
projects. Whether you're a complete beginner or you already
have some programming experience, this book is designed to
help you build a strong foundation in JavaScript.
Page 13
Take a moment to review the suggested answer and try to
understand where you went wrong. It's important to
remember that many coding errors seem obvious once you've
found them, but they can still take a great deal of time to
locate. Be patient with yourself and don't get discouraged. This
is all part of the learning process, and every new developer
goes through it.
So, what are you waiting for? Let's dive in and start coding!
Page 14
Section 1: JavaScript Quick Start
Introduction
JavaScript is a programming language that's like a Swiss Army
knife: it can be used for all sorts of things, from creating
interactive web pages to building complex web applications
and even running on servers. As a JavaScript developer, you'll
have a lot of power in your hands to create cool and useful
things.
Page 15
Choosing a Text Editor
The first thing you'll need is a text editor. A text editor is a
software application that allows you to write and edit text,
including code. There are many options to choose from, both
free and paid.
Editing a Text File in Visual Studio Code from Microsoft. This free
editor is used by millions of professional developers.
Each text editor has its own strengths and weaknesses, so it's
worth trying a few out to see which one you like best. I
personally use Visual Studio Code and highly recommend it!
Page 16
Creating an HTML File
Before we can write JavaScript code, we need a web page to
run it on. In order to create a web page, we'll need to write
some HTML code.
<!DOCTYPE html>
<html>
<head>
<title>My JavaScript Page</title>
</head>
<body>
<h1>Hello, world!</h1>
<script src="main.js"></script>
</body>
</html>
This HTML file sets up a basic web page with a heading and a
reference to a JavaScript file called main.js. We'll create the
main.js file in the next section.
console.log("Hello, world!");
Page 17
Linking JavaScript to HTML
Now that we have our HTML file and our JavaScript file, we
need to link them together. In our HTML file, we already added
a reference to our main.js file in the body section. This tells the
browser to load the JavaScript file and run any code it contains.
Page 18
This will open the browser's developer tools. From there, you
can select the "Console" tab to access the console.
Once you have the console open, you can enter JavaScript
code directly into the console and press Enter to run it. Here's
an example:
console.log("Hello, world!");
<!DOCTYPE html>
<html>
<head>
<title>My JavaScript Page</title>
</head>
<body>
<h1>Hello, world!</h1>
<script src="main.js"></script>
</body>
</html>
Page 19
Using a Code Editor
If you're working on a larger JavaScript project, you may want
to use a code editor to write and run your code. Code editors
like Visual Studio Code or Sublime Text allow you to write and
run JavaScript code directly in the editor, without the need for
a web browser.
Most code editors have built-in features for running and testing
your code. For example, in Visual Studio Code, you can use the
built-in debugger to step through your code and find any
errors.
Page 20
We’ll revisit many of these concepts later and in greater detail,
but, I want to get you moving with JavaScript– and actually
coding– as soon as possible!
Console.log
Initially in this work book, we’ll be logging our JavaScript
results ot the browser console. This avoids having to introduce
confusing code earlier than you’re ready for it.
Page 21
The console.log() results are shown on the right in the browser
window.
Once you have the console open, you can use console.log() to
print messages or values to the console. Here's an example:
console.log("Hello, world!");
let x = 5;
let y = 10;
console.log(x + y);
Page 22
explanation helps you get started with using the console in
your JavaScript projects!
Variables
Variables are used to store data in JavaScript. They're like
labeled boxes that hold values that can be changed. Here's an
example:
Data Types
JavaScript has several built-in data types, including strings,
numbers, booleans, arrays, and objects. Let's go over each one
briefly.
Strings
Strings are used to represent text in JavaScript. They are
enclosed in either single quotes (') or double quotes ("). Here's
an example:
Page 23
console.log(myString);
Numbers
Numbers are used to represent numeric values in JavaScript.
They can be integers or floating-point numbers. Here's an
example:
Booleans
Booleans are used to represent true/false values in JavaScript.
They can be either true or false. Here's an example:
Arrays
Arrays are used to store collections of data in JavaScript. They
are enclosed in square brackets ([]). Here's an example:
Objects
Objects are used to represent complex data structures in
JavaScript. They are enclosed in curly braces ({}) and consist of
key-value pairs. Here's an example:
Page 24
Operators
Operators are used to perform operations on values in
JavaScript. There are several types of operators, including
arithmetic, comparison, and logical operators.
Arithmetic Operators
Arithmetic operators are used to perform basic math
operations in JavaScript. Here are some examples:
let x = 10;
let y = 5;
console.log(x + y); // outputs 15
console.log(x - y); // outputs 5
console.log(x * y); // outputs 50
console.log(x / y); // outputs 2
Comparison Operators
Comparison operators are used to compare values in
JavaScript. They return a boolean value (true or false). Here are
some examples:
let x = 10;
let y = 5;
console.log(x);
Logical Operators
Logical operators are used to combine boolean values in
JavaScript. There are three logical operators: && (and), || (or),
and ! (not). Here are some examples:
Page 25
let x = 10;
let y = 5;
console.log(x > 5 && y < 10); // outputs true
console.log(x > 5 || y > 10); // outputs true
console.log(!(x > 5)); // outputs false
Functions
Functions are reusable blocks of code that perform a specific
task. They can take input (called parameters) and return
output. Here's an example:
function sayHello(name) {
console.log("Hello, " + name + "!");
}
Code Exercises
It may be premature to provide code exercises at this point–
You’ve only just started. However, I did decide to include some
here so you can see the types of problems you’ll be solving with
Page 26
JavaScript. You’re welcome to give them a shot, or wait and
come back when you have a more solid footing.
As wil all code exercsies, the answers are in the back of the
book! Good luck.
Page 27
4. Log the result of checking if a is equal to b to the
console.
5. Log the result of checking if a is not equal to b to the
console.
Page 28
Section 2: Variables and Data
Types
Introduction
In this section, we'll be diving into the wonderful world of
variables and data types. If you're new to programming, these
concepts might seem a bit confusing at first, but fear not - we'll
take it step by step and make sure you understand everything
before moving on.
Page 29
So buckle up, grab a cup of coffee (or tea, we don't judge), and
let's dive into variables and data types in JavaScript!
Declaring Variables
In JavaScript, variables are used to store data values. In this
section, we'll go over the basics of declaring variables in
JavaScript, including different variable types and naming
conventions.
Variable Types
JavaScript has several different variable types, including:
Naming Conventions
When naming variables in JavaScript, there are some
conventions to follow to make your code more readable and
understandable. Here are a few tips:
Page 30
Use descriptive variable names that describe the purpose of
the variable.
● Start variable names with a lowercase letter.
● Use camelCase to separate words within a variable
name.
● Avoid using reserved keywords as variable names (e.g.
let, if, while, etc.)
Page 31
console.log(myNumber);
Best Practices
When declaring variables in JavaScript, it's important to follow
some best practices to ensure that your code is clean, readable,
and error-free. Here are a few tips:
Strings
Strings are used to represent text in JavaScript. They can be
created using either single or double quotes, like this:
Page 32
In addition to single and double quotes, you can also create
strings using backticks (`), which allow you to include variables
and expressions inside the string using ${...} syntax:
Numbers
Numbers are used to represent numeric values in JavaScript.
They can be integers or decimals, positive or negative. Here's
an example:
Page 33
Booleans
Booleans are used to represent true/false values in JavaScript.
They can be either true or false. Here's an example:
Null
Null is a special value in JavaScript that represents a deliberate
non-value. It is often used to indicate that a variable has no
value or that an object property does not exist. Here's an
example:
Undefined
Undefined is a value in JavaScript that indicates that a variable
has been declared but has not yet been assigned a value.
Here's an example:
let myUndefined;
console.log(myUndefined); // Output: undefined
In this code, we're declaring a variable called myUndefined but
not assigning it a value. When we print the value of
myUndefined to the console, we get the value undefined.
Page 34
Complex Data Types
In addition to the primitive data types covered in the previous
section, JavaScript also has several complex data types. These
data types are "complex" because they are objects and have
methods and properties of their own.
Arrays
Arrays are used to store collections of data in JavaScript. They
can be created using square brackets and can contain any
combination of data types, including other arrays. Here's an
example:
myArray.pop();
console.log(myArray); // Output: ['apple', 'banana',
'orange']
Page 35
Objects
Objects are used to store collections of key-value pairs in
JavaScript. They can be created using curly braces and can
contain any combination of data types, including other objects.
Here's an example:
let myObject = {
name: 'John',
age: 30,
hobbies: ['reading', 'running', 'cooking'],
};
let myObject = {
name: 'John',
age: 30,
hobbies: ['reading', 'running', 'cooking'],
};
Page 36
Functions
Functions are used to encapsulate blocks of code and can be
called or invoked at any time. They can take parameters and
return values. Here's an example:
function addNumbers(a, b) {
return a + b;
}
Page 37
Type Coercion
Type coercion is the process of converting a value from one
data type to another implicitly. This can happen when you
perform an operation between two different data types. For
example:
Type Conversion
Type conversion is the process of explicitly converting a value
from one data type to another. This can be done using built-in
JavaScript functions, such as Number(), String(), and Boolean().
For example:
console.log(myNumber); // Output: 5
Page 38
// Converting a number to a string
let myNumber = 5;
let myString = String(myNumber);
console.log(myNumber); // Output: 1
Loose equality (==) compares two values for equality after type
coercion, while strict equality (===) compares two values for
equality without type coercion.
Here's an example:
Page 39
It's generally considered best practice to use strict equality
whenever possible to avoid unexpected behavior.
Critical Points
Declaring variables:
Page 40
● Be aware of type coercion when performing operations
between different data types, as it can lead to
unexpected results.
The FAQ
Q: What is the difference between let, const, and var for
declaring variables?
A: let and const are block-scoped variables, while var is
function-scoped. let variables can be reassigned, while const
variables cannot. It's generally recommended to use const for
variables that won't be reassigned, and let for variables that
might be reassigned.
Page 41
A: Loose equality (==) compares two values for equality after
type coercion, while strict equality (===) compares two values
for equality without type coercion. It's generally recommended
to use strict equality whenever possible to avoid unexpected
behavior.
Code Exercises
Page 42
Exercise 2.3: Declaring and Assigning Variables
Declare two variables, firstName and lastName, and assign
them your first and last name, respectively. Then, concatenate
the two variables together and print the result to the console.
Then, print the value of the second hobby in the array to the
console, and add a new key-value pair to the object called
occupation with your current or desired occupation. Finally,
print the entire object to the console.
Page 43
Section 3: Control Flow and Loops
Introduction
Welcome to Section 3 of the JavaScript Workbook! In this
section, we'll be covering control flow and loops, two essential
concepts in programming.
Conditional Statements
In programming, we often need our programs to make
decisions based on certain conditions. That's where conditional
statements come in. In this section, we'll be covering two types
of conditional statements in JavaScript: if/else statements and
switch/case statements.
Page 44
If/Else Statements
If/else statements are a fundamental part of programming, and
they allow your program to execute different code blocks
depending on whether a certain condition is true or false.
Here's an example:
if (myNumber > 0) {
console.log('myNumber is positive');
} else {
console.log('myNumber is negative or zero');
}
if (myNumber > 0) {
console.log('myNumber is positive');
} else if (myNumber < 0) {
console.log('myNumber is negative');
} else {
console.log('myNumber is zero');
}
Page 45
Switch/Case Statements
Switch/case statements are another way of controlling the flow
of your program based on different conditions. They're often
used when you have multiple conditions to check. Here's an
example:
switch (dayOfWeek) {
case 'Monday':
console.log('It\'s Monday!');
break;
case 'Tuesday':
console.log('It\'s Tuesday!');
break;
case 'Wednesday':
console.log('It\'s Wednesday!');
break;
default:
console.log('It\'s some other day!');
}
Page 46
The prompt() Function
The prompt() function is a built-in function in JavaScript that
allows you to ask the user for input via a pop-up window. Here's
an example of how to use the prompt() function to ask the user
for their name:
Code Exercises
Exercise 3.1: Odd or Even (with Modulus)
Write a program that asks the user for a number and checks
whether it's odd or even. If the number is even, the program
should print "The number is even." If it's odd, the program
should print "The number is odd." Use an if/else statement to
accomplish this, and don't forget about the modulus operator
(%), which can help you determine whether a number is even
or odd.
Page 47
Exercise 3.2: Grade Converter
Write a program that asks the user for a grade (a number
between 0 and 100) and converts it to a letter grade using the
following scale:
90-100: A
80-89: B
70-79: C
60-69: D
Below 60: F
Use a switch/case statement to accomplish this.
In this example, the for loop will execute the block of code
inside the curly braces five times. The loop starts with i equal to
0, and then increments i by 1 on each iteration until i reaches 4.
The output of this code will be:
Page 48
0
1
2
3
4
let i = 0;
while (i < 5) {
console.log(i);
i++;
}
In this example, the while loop will execute the block of code
inside the curly braces as long as i is less than 5. The loop starts
with i equal to 0, and then increments i by 1 on each iteration
until i reaches 4. The output of this code will be:
0
1
2
3
4
Page 49
let i = 0;
do {
console.log(i);
i++;
} while (i < 5);
0
1
2
3
4
Page 50
to understand the strengths and weaknesses of each type of
loop so you can choose the right one for the task at hand. In
the next section, we'll cover loop control statements that allow
you to modify the behavior of loops and make them more
powerful.
Code Exercises
To complete these exercises you’re going to need to make
JavaScript do a bit of math:
Page 51
Write a for loop that prints out 5 random numbers between 1
and 10.
Page 52
if (i === 5) {
break;
}
console.log(i);
}
Page 53
for (let i = 1; i <= 10; i++) {
if (i % 2 === 0) {
continue;
}
if (i === 7) {
break;
}
console.log(i);
}
Coding Exercises
Exercise 3.7: Find the first even number
Write a program that uses a for loop to find the first even
number in an array of integers. Once you've found the first
even number, use the break statement to exit the loop and log
the even number to the console.
Page 54
Critical Points
Conditional Statements:
Iteration Statements:
● Allow you to repeat a block of code until a certain
condition is met.
● The most common types are for loops, while loops, and
do/while loops.
● For loops are used when you know the number of times
you want to repeat a block of code.
● While loops are used when you want to repeat a block
of code until a certain condition is met, and you don't
know how many times you'll need to repeat it.
● Do/while loops are similar to while loops, but the block
of code is executed at least once even if the condition is
initially false.
Page 55
The FAQ
Q: What is the difference between a for loop and a while loop?
A: For loops are used when you know the exact number of
times you want to repeat a block of code. While loops, on the
other hand, are used when you want to repeat a block of code
until a certain condition is met, and you may not know the
exact number of times you'll need to repeat it.
Page 56
Section 4: JavaScript Functions
Introduction
Welcome to Section 4, where we'll dive into the wonderful
world of functions in JavaScript. Functions are an essential part
of any programming language and can be incredibly powerful
tools for writing efficient and reusable code.
Page 57
Declaring Functions
Functions are like superheroes in the programming world.
They have the power to take on any task and make your code
more efficient and reusable. But before we can start using
functions to save the day, we need to understand how to
declare and call them in JavaScript.
function greet(name) {
console.log("Hello, " + name + "!");
}
Calling Functions
Now that we've declared our function, we can call it to execute
the code inside it. Here's how we would call our greet function:
greet("Bob");
// Output: Hello, Bob!
Page 58
Function Return Values
So far, our greet function has been using console.log() to
output a greeting to the console. But what if we want our
function to return a value that we can use elsewhere in our
code?
function add(a, b) {
return a + b;
}
And there you have it! That's the basics of declaring and calling
functions in JavaScript. Keep these concepts in mind as we
move on to the more advanced topics in the following sections.
Page 59
function. In this section, we'll explore how to define and use
function parameters and arguments.
greet('Alice', 25);
// Output: Hello Alice, you are 25 years old!
Page 60
Default Parameter Values
In some cases, you may want to provide a default value for a
function parameter in case no argument is provided. This can
be done by using the assignment operator (=) when defining
the function parameter. Here's an example:
Rest Parameters
Sometimes, you may want to define a function that can accept
a variable number of arguments. This can be done using the
rest parameter syntax, which allows you to define a parameter
that will receive an array of all remaining arguments passed to
the function. Here's an example:
function sum(...numbers) {
let result = 0;
for (let i = 0; i < numbers.length; i++) {
result += numbers[i];
}
console.log(`The sum is ${result}`);
}
Page 61
Function parameters and arguments are an essential part of
JavaScript programming. By defining and using function
parameters, you can create reusable and flexible functions that
can be used in a variety of contexts.
Code Exercises
Exercise 4.1: Calculator
Write a function called calculator that takes in two numbers
and a string representing an operation (+, -, *, /) and returns the
result of that operation. Use a switch statement to handle the
different operations.
Page 62
Function expressions and arrow functions
So far, we've been declaring our functions using the function
keyword followed by the function name and the function body
in curly braces. However, there are other ways to declare
functions in JavaScript that can be more concise and easier to
read.
Function Expressions
A function expression is a way of defining a function as a
variable assignment. The variable can then be called like a
function. Here's an example:
Arrow Functions
Arrow functions are a shorthand way of declaring functions
that were introduced in ECMAScript 6 (ES6). They use a
different syntax and have some differences in how this is
handled. Here's an example:
Page 63
In this example, we're declaring the add function using the
arrow function syntax. The function parameters are enclosed in
parentheses, followed by the arrow => and then the function
body in curly braces.
console.log(square(4)); // Output: 16
Code Exercise
Exercises 4.6: Rewrite as Arrow Functions
Rewrite the following traditional JavaScript functions asarrow
functions.
Function A
function multiplyByTwo(num) {
return num * 2;
}
Page 64
Function B
function addNumbers(num1, num2) {
return num1 + num2;
}
Function C
function greeting(name) {
return "Hello, " + name + "!";
}
Function Scope
When you declare a variable inside a function, it's only
accessible inside that function. This is called function scope. It
means that the variable is only defined within the function's
curly braces, and any attempts to access it from outside the
function will result in an error.
Page 65
myFunction();
console.log(myVar);
Global Scope
Variables declared outside of any function have global scope,
which means they can be accessed from anywhere in your
code, including inside functions. It's generally a good idea to
avoid using global variables as they can be accessed and
modified from anywhere in your code, which can lead to
unexpected bugs.
function myFunction() {
console.log(myGlobalVar);
}
myFunction();
console.log(myGlobalVar);
Page 66
Closures
A closure is created when a function is defined inside another
function and has access to the outer function's variables. In
other words, the inner function "closes over" the variables of
the outer function. This allows us to create private variables and
functions that are not accessible from outside the outer
function.
function innerFunction() {
console.log(outerVar);
}
return innerFunction;
}
Page 67
Code Exercises
Exercise 4.7 Calculator
Write a function called calculator that takes in two numbers
and a string representing an operation (+, -, *, /) and returns the
result of that operation. Use a switch statement to handle the
different operations.
Critical Points
Functions
● A function is a reusable block of code that performs a
specific task.
● Functions are declared using the function keyword,
followed by the function name, and a set of parentheses
that can optionally contain parameters.
● To call a function, use the function name followed by
parentheses and any necessary arguments.
● Functions can return values using the return keyword.
Page 68
● Functions can be declared as function expressions,
which allow them to be assigned to variables, passed as
arguments to other functions, and used as return
values.
● Arrow functions are a shorthand syntax for declaring
function expressions.
● Functions have their own scope, meaning variables
declared within a function are only accessible within
that function.
Page 69
● Functions have their own scope, meaning variables
declared within a function are only accessible within
that function.
● Variables declared outside of any function are said to
have global scope, and can be accessed from anywhere
in the code.
● Closures are created when a function is declared inside
another function, and the inner function has access to
the outer function's variables and parameters.
● Closures allow for powerful programming patterns such
as private variables and encapsulation, but can also lead
to memory leaks if not used carefully.
The FAQ
Q: How do I pass arguments to a function?
A: When you call a function, you can pass any number of
arguments by including them in the parentheses separated by
commas. For example, myFunction(1, "hello", true) would pass
the values 1, "hello", and true as arguments to the function.
Page 70
A: Function declarations are defined using the function
keyword and are hoisted to the top of their scope. This means
they can be called before they are defined. Function
expressions, on the other hand, are defined as variables and are
not hoisted. They must be defined before they are called.
Page 71
Section 5: Working with Arrays
Arrays are one of the most fundamental data structures in
computer science, and they're a vital tool for any programmer.
In JavaScript, arrays can hold a mix of different types of data
and can be manipulated in a variety of ways.
Declaring Arrays
Declaring an array in JavaScript is as simple as using the "let"
keyword followed by the array name and square brackets.
Arrays can hold a mixture of different data types including
strings, numbers, and even other arrays. Here's an example:
Page 72
You can also use the new keyword to create an array. In this
case, you pass the elements of the array as arguments to the
Array constructor. This method is less common than the literal
notation, but it can be useful in certain situations.
Initializing Arrays
Initializing an array is simply the process of adding values to it.
There are a couple of ways to do this in JavaScript. One way is
to use the square bracket notation to assign values to specific
indexes in the array. Here's an example:
Page 73
let myArray = ['apple', 'banana', 'orange'];
Page 74
4]
Multidimensional Arrays
In addition to single-dimensional arrays, JavaScript also
supports multidimensional arrays. A multidimensional array is
essentially an array of arrays. Here's an example:
const grid = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
In this example, the first index (1) refers to the second row of
the grid array, and the second index (2) refers to the third
column of that row.
Page 75
example, to change the value of the element in the second row
and third column of the grid array, you would use the following
syntax:
grid[1][2] = 42;
fruits.unshift('grape');
console.log(fruits); // output: ['grape', 'apple',
'banana', 'orange', 'pear']
Page 76
Removing Elements with pop() and shift()
pop() and shift() are the counterpart to push() and unshift(),
respectively. They remove elements from the end and
beginning of an array.
fruits.shift();
console.log(fruits); // output: ['banana', 'orange']
Here are a few more methods you can use with arrays that you
may find useful:
Page 77
console.log(fruits.indexOf('banana')); // output: 1
console.log(fruits.indexOf('grape')); // output: -1
Page 78
const colors = ['red', 'green', 'blue', 'yellow',
'purple'];
const removedColors = colors.splice(1, 2, 'orange',
'pink'); // ['green', 'blue']
console.log(colors); // ['red', 'orange', 'pink',
'yellow', 'purple']
console.log(removedColors); // ['green', 'blue']
Page 79
you can specify a different separator as an argument to the
method.
Here's an example:
const fruits = ['apple', 'banana', 'cherry'];
const fruitsString = fruits.join(', ');
Here's an example:
const fruitsString = 'apple, banana, cherry';
const fruitsArray = fruitsString.split(', ');
Page 80
Iterating Through Arrays with For and
While Loops
In addition to declaring and initializing arrays, you will often
need to iterate over the elements in an array to perform some
operation on each one. Two common ways to do this are with
for and while loops. In this section, we will explore how to use
these loops to iterate over arrays, perform operations on the
elements, and store the results in a new array. This is a
fundamental concept in programming and an essential skill for
any JavaScript developer. Let's dive in!
Page 81
red
green
blue
let i = 0;
while (i < array.length) {
// do something with array[i]
i++;
}
Page 82
This loop will print:
forEach()
The forEach() method is used to execute a function for each
element in an array. The syntax for forEach() is as follows:
Page 83
numbers.forEach(function(number) {
console.log(number);
});
map()
The map() method is used to create a new array with the
results of calling a function for each element in an array. The
syntax for map() is as follows:
Page 84
return number * 2;
});
console.log(doubledNumbers);
[2, 4, 6, 8, 10]
filter()
The filter() method is used to create a new array with all
elements that pass a certain condition. The syntax for filter() is
as follows:
Page 85
});
console.log(evenNumbers);
[2, 4]
Code Exercises
Exercise 5.1: Array Practice
In this lab, you will practice declaring and initializing arrays, as
well as accessing their elements.
Page 86
4. Use the unshift() method to add the value 'pear' to the
beginning of the array
5. Use the shift() method to remove the first value from
the array
6. Use the splice() method to remove the value 'banana'
from the array
7. Use the slice() method to create a new array called
newFruits that contains the values 'apple' and 'cherry'
Page 87
2. Use the filter() method to create a new array called
evens that contains only the even numbers from the
numbers array
3. Print the evens array to the console
Requirements:
Critical Points
Declaring and initializing arrays:
● Arrays are a type of object that can hold multiple values
of different types.
● Use the square bracket notation to declare an array and
initialize it with values.
Declaring Arrays:
● Declare a new array using the square bracket notation.
● Arrays can contain values of any data type.
Page 88
● Use the length property to find the number of elements
in an array.
Initializing Arrays:
● Initialize an array by providing a comma-separated list
of values inside the square brackets.
● Arrays can also be initialized with values using the new
Array() constructor.
Multidimensional Arrays:
● A multidimensional array is an array of arrays.
● Use nested square brackets to access elements of a
multidimensional array.
Page 89
● Use the map() method to create a new array based on
an existing array.
● Use the filter() method to create a new array based on a
condition.
● Use the reduce() method to apply a function to each
element of an array and return a single value.
The FAQ
Q: What is an array?
A: An array is a special variable in JavaScript that can hold
multiple values.
Page 90
index. The slice() method can be used to create a new array
that contains a subset of the values in the original array.
Page 91
Section 6: Objects in JavaScript
Welcome to Section 6 of our JavaScript Development
Workbook! In this section, we will be diving into one of the
most important and complex topics in JavaScript: Objects. Just
like in real life, objects in programming are essential tools that
allow us to organize and manage information in a logical way.
And, just like in real life, they can be a bit tricky to wrap your
head around at first.
Built-In Objects
JavaScript has several built-in objects that are available by
default. These objects include:
Page 92
String: provides methods for working with strings
Array: provides methods for working with arrays
Object: the base object for all JavaScript objects
These built-in objects can be accessed and used directly in
your code.
Custom Objects
In addition to the built-in objects, you can also create your own
custom objects in JavaScript. Custom objects can have their
own properties and methods, just like built-in objects.
Page 93
Prototypal inheritance allows you to create more efficient and
organized code by reusing existing code instead of creating
new objects from scratch.
Page 94
In our architectural analogy, we can think of the constructor
function as the construction crew that builds the building
based on the architectural plans. Each time the crew builds a
new building, it uses the same set of plans, but the resulting
building is unique, with its own specific values for its features.
Object Literals
Object literals are a simple and concise way to create objects in
JavaScript. An object literal is defined using curly braces {} and
consists of key-value pairs separated by commas. The keys in
an object literal are strings, and the values can be of any data
type, including other objects.
Page 95
const person = {
name: 'John',
age: 30,
address: {
street: '123 Main St',
city: 'Anytown',
state: 'CA'
}
};
Constructors
Constructors are functions that create new objects. To create a
new object using a constructor, you use the new keyword
followed by the name of the constructor function. Constructors
are named with a capitalized first letter to distinguish them
from regular functions.
Page 96
refers to the new object being created, and the properties of
the object are set to the values passed in as arguments.
Overall, both object literals and constructors are useful tools for
creating objects in JavaScript, and the choice between them
depends on the specific needs of your program.
Accessing Properties
Properties are like adjectives that describe an object. They can
be accessed and modified using dot notation or bracket
notation. For example, let's say we have an object called person
with properties name, age, and occupation:
let person = {
name: "John Doe",
age: 35,
occupation: "Web Developer"
Page 97
};
Modifying Properties
Properties can be modified using the same syntax as accessing
them. For example, we can change the occupation property of
our person object like this:
Adding Properties
New properties can be added to an object using dot
notation or bracket notation. For example, let's add a
location property to our person object:
Methods
Methods are like verbs that describe what an object can do.
They are functions that are associated with an object and can
be called to perform a specific action. For example, let's add a
greet method to our person object:
let person = {
name: "John Doe",
age: 35,
Page 98
occupation: "Web Developer",
greet: function() {
console.log("Hello, my name is " + this.name +
".");
}
};
Introduction to Prototypes
In JavaScript, every object has a prototype, which is a reference
to another object. The prototype object acts as a template for
the object and contains the object's properties and methods.
When a property or method is called on an object, JavaScript
first looks for that property or method on the object itself. If it's
not found, it looks for it on the prototype object. If it's still not
found, it looks for it on the prototype's prototype, and so on,
until it reaches the root prototype object. This is called the
prototype chain.
Page 99
Creating a Prototype Object
You can create a prototype object using the Object()
constructor or by using an object literal. For example:
Page 100
prototype object, and so on, until it reaches the root prototype
object.
class Vehicle {
constructor(make, model, year) {
Page 101
this.make = make;
this.model = model;
this.year = year;
}
getInfo() {
return `Make: ${this.make}, Model: ${this.model},
Year: ${this.year}`;
}
}
getInfo() {
return `${super.getInfo()}, Has Siren:
${this.hasSiren}`;
}
Page 102
useSiren() {
console.log('WEE-OOH WEE-OOH');
}
}
getInfo() {
return `${super.getInfo()}, Number of Seats:
${this.numSeats}`;
}
driveToWork() {
console.log(`Starting the engine of the
${this.make} ${this.model} and driving to work with
${this.numSeats} seats!`);
}
}
Page 103
returned string. We've also defined a unique method for the
Bus class called driveToWork() that logs a message to the
console indicating the vehicle is being driven to work.
Creating an Ambulance
Let's start by creating an instance of the Ambulance class. We
can do this by calling the constructor function and passing in
the required parameters:
Creating a Bus
Next, let's create an instance of the Bus class. We can do this in
a similar way to creating an Ambulance:
Page 104
Using the Methods
Now that we have our objects created, we can start using the
methods we defined in our classes.
console.log(ambulance.maxDistance());
// Output: The maximum distance this ambulance can
travel on a full tank of gas is 480 miles.
bus.boardPassenger();
console.log(bus.passengers);
// Output: 1
ambulance.blowHorn();
// Output: WEEEE-OOOO-WEEEE-OOOO
Inheritance in Action
Remember that because the Ambulance and Bus classes
inherit from the Vehicle class, they have access to all of the
properties and methods defined in that class as well. For
example, we can call the start method on both the ambulance
and bus objects to start the engines:
ambulance.start();
Page 105
// Output: The Ford Ambulance from 2015 is starting up.
bus.start();
// Output: The Volvo Bus from 2020 is starting up.
Code Exercises
Code Exercise 6.1: Creating a Class
In this exercise, you will create a class in JavaScript and perform
an interesting operation on it.
Page 106
4. Create two subclasses of the Vehicle class called Car
and Truck.
5. The Car subclass should have a method called drive()
that logs a message to the console indicating that the
car is driving.
6. The Truck subclass should have a method called haul()
that logs a message to the console indicating that the
truck is hauling something.
7. Create at least one instance of each subclass with
unique makes and models.
8. Call the honk() method on each instance of the Vehicle
class and observe the output in the console.
9. Call the drive() method on the Car instance and observe
the output in the console.
10. Call the haul() method on the Truck instance and
observe the output in the console.
Critical Points
Built-in JavaScript Objects Versus Custom Objects:
● Built-in objects are pre-defined objects in JavaScript,
like Array, Date, and Math.
● Custom objects are objects that you define and create
yourself.
● Both types of objects can have properties and methods.
Page 107
● Methods are the actions or behaviors that an object can
perform.
● Properties and methods are accessed using dot
notation or bracket notation.
The FAQ
Q: What is an object in JavaScript?
A: An object is a collection of properties and methods,
represented as key-value pairs, that can be used to store and
manipulate data in JavaScript.
Page 108
Q: How do I inherit properties and methods in JavaScript?
A: In JavaScript, you can use prototypes to inherit properties
and methods from existing objects. You can create a new
object that is linked to an existing object, and then add or
override properties and methods as needed.
Page 109
Section 7: Error Handling
As much as we strive to write perfect code, it's inevitable that
errors will arise at some point. Whether it's a syntax error,
runtime error, or a logic error, knowing how to effectively
handle errors is crucial to ensuring our programs run smoothly.
In this section, we'll cover the different types of errors you may
encounter in JavaScript, including syntax, runtime, and logic
errors. We'll also explore how you can use developer tools in
your browser to help identify and debug errors in your code.
Syntax Errors
Syntax errors occur when you have incorrect syntax in your
code. For example, if you forget to close a parenthesis or add
an extra semicolon, you will get a syntax error. These errors are
detected by the JavaScript interpreter during the compilation
phase, before the code is executed. Here's an example of a
syntax error:
function addNumbers(a, b) {
Page 110
return a + b;
// syntax error: missing closing curly brace
Runtime Errors
Runtime errors occur during the execution of your code. These
errors happen when JavaScript is unable to complete an
operation due to unexpected input, such as trying to divide by
zero or accessing a variable that does not exist. Runtime errors
can cause your code to crash, so it's important to handle them
properly. Here's an example of a runtime error:
function divide(a, b) {
return a / b;
}
Logic Errors
Logic errors are the most subtle type of error and can be the
most difficult to track down. These errors occur when your
code executes without errors, but does not produce the
expected result. Logic errors are caused by flaws in the design
or implementation of your code. Here's an example of a logic
error:
function calculateArea(radius) {
return 3.14 * radius * radius;
}
Page 111
It's important to know the different types of errors so that you
can properly diagnose and fix issues in your code. In the next
sections, we'll explore how to handle errors using
try/catch/finally statements and throwing and catching
exceptions.
console.log("Hello, world!");
Tracing Variables
Another useful feature of the developer tools is the ability to
trace variables. This allows you to see the value of a variable at
any point in your code. To do this, you can use the console.log()
method to log the value of the variable to the console.
For example:
Page 112
let x = 5;
console.log(x);
Inserting Breakpoints
Sometimes, you may need to pause your code at a specific
point in order to debug it. To do this, you can insert a
breakpoint in your code using the developer tools.
Code Exercise
Code Exercise 7.1: Inserting Breakpoints
In this lab, you will practice inserting breakpoints in JavaScript
code using developer tools to locate and fix an error.
<html>
<head>
<script src="script.js"></script>
</head>
<body>
<h1>Inserting Breakpoints Lab</h1>
Page 113
</body>
</html>
function calculateSum(arr) {
var sum = 0;
for (var i = 0; i <= arr.length; i++) {
sum += arr[i];
}
return sum;
}
The error in this code is that the for loop in the calculateSum
function is iterating one too many times, resulting in an
undefined value being added to the sum.
3) Open the HTML file in your browser and open the developer
tools (typically accessed by right-clicking on the page and
selecting "Inspect" or pressing F12 on Windows or
Option-Command-I on Mac).
Page 114
5) Find the line with the error (in this case, line 3 of the
calculateSum function) and click on the line number to insert a
breakpoint.
6) Refresh the page in your browser to run the code with the
breakpoint.
8) Once you have identified and fixed the error, remove the
breakpoint and refresh the page to run the code again without
pausing at the breakpoint.
Page 115
9) Check the console output to ensure that the error has been
resolved and the code is running correctly.
try/catch/finally statements
In JavaScript, the try/catch/finally statements provide a way to
handle errors that may occur in your code.
try {
// Code that may throw an error
} catch (error) {
// Code to handle the error
}
try {
// Code that may throw an error
} catch (error) {
// Code to handle the error
}
Page 116
The finally Block
The finally block is optional and is used to specify a block of
code that will always be executed, regardless of whether an
error was thrown or not. This block is often used for cleanup
code, such as closing a database connection or releasing
resources.
try {
// Code that may throw an error
} catch (error) {
// Code to handle the error
} finally {
// Code that will always be executed
}
function divide(a, b) {
try {
if (b === 0) {
throw new Error("Cannot divide by zero!");
}
return a / b;
} catch (error) {
console.error(error);
return null;
} finally {
console.log("Division operation complete.");
}
}
Page 117
In this example, the try block contains the code that may throw
an error, which is the division of two numbers. If the second
number is zero, the throw statement will create a new Error
object with a message indicating that the division is not
possible. The catch block contains code to handle this error,
which logs the error message to the console and returns null.
The finally block contains code to always be executed, which
logs a message indicating that the division operation is
complete.
Code Exercise
Code Exercise 7.2: Try/Catch/Finally
In this lab, you will practice using the try/catch/finally
statements to handle errors in your JavaScript code.
Page 118
4) Test your program by intentionally causing errors and
verifying that they are handled correctly by the try/catch/finally
blocks.
5) Once you have verified that your code works correctly, try to
modify the divide function to throw a different type of error
and observe the behavior of the try/catch/finally blocks.
Here's an example:
function divideByZero(num1, num2) {
if (num2 === 0) {
throw "Cannot divide by zero!";
} else {
return num1 / num2;
}
}
try {
console.log(divideByZero(10, 0));
} catch (error) {
console.log("Error: " + error);
}
Page 119
In this example, the divideByZero function checks if the second
parameter is 0, and if it is, it throws an exception with the
message "Cannot divide by zero!". In the try block, we call the
divideByZero function with arguments 10 and 0. Since the
second argument is 0, an exception is thrown. This exception is
caught in the catch block, where we log the error message to
the console.
Here's an example:
try {
let myVar = someFunctionThatMightThrowAnError();
console.log(myVar);
} catch (error) {
console.log("An error occurred: " + error);
}
Here's an example:
try {
console.log("Executing try block");
Page 120
throw "An error occurred";
} catch (error) {
console.log("An error occurred: " + error);
} finally {
console.log("Executing finally block");
}
Code Exercise
Code Exercise 7.3: Throwing Exceptions
Page 121
5) In the console tab of the developer tools, you should see an
error message with the stack trace and the message
"Something went wrong".
Critical Points
Types of Errors:
● Syntax errors occur when code does not follow the
correct syntax of the programming language
● Runtime errors happen when code runs but encounters
an unexpected behavior
● Logic errors occur when code produces an unexpected
result, but no error is thrown
try/catch/finally Statements:
● try/catch/finally statements provide a way to handle
errors that may occur in JavaScript code
● The try block contains the code to be executed, and the
catch block contains the code to be executed if an error
occurs
Page 122
● The finally block contains the code that will be executed
regardless of whether an error occurs or not
The FAQ
Q: What are the most common types of errors in JavaScript?
A: The most common types of errors in JavaScript are syntax
errors, runtime errors, and logical errors. Syntax errors occur
when the code is not written according to the proper syntax
rules. Runtime errors occur when the code is executing and
encounters an unexpected condition. Logical errors occur
when the code executes but produces unexpected results.
Page 123
will execute whether or not an error occurs. These statements
allow you to gracefully handle errors in your code and prevent
the code from crashing.
Page 124
Section 8: DOM Manipulation
In this section, we'll cover the basics of the DOM, including how
to access and modify DOM elements using JavaScript, how to
change the styling of elements with CSS, and how to respond
to user events. By the end of this section, you'll have a solid
understanding of the DOM and how to use it to create
dynamic and interactive web pages with JavaScript. So let's
dive in and start exploring the amazing world of DOM
manipulation!
Page 125
JavaScript, we can add interactivity and dynamic behavior to a
web page.
getElementById()
The getElementById() method is used to select a single
element by its unique ID. To use this method, simply pass the
ID of the element you want to select as a string:
querySelector()
The querySelector() method is used to select a single element
based on a CSS selector. This method returns the first element
that matches the selector:
Page 126
querySelectorAll()
The querySelectorAll() method is used to select all elements
that match a CSS selector. This method returns a NodeList
object, which is similar to an array:
const myElements =
document.querySelectorAll(".my-class");
Page 127
<!DOCTYPE html>
<html>
<head>
<title>Change Paragraph Text</title>
<style>
/* Add some basic styles to the paragraph */
p {
font-size: 24px;
color: navy;
font-weight: bold;
text-align: center;
}
</style>
</head>
<body>
<p id="my-paragraph">This is the original
text.</p>
<script>
// Define a function that will change the text of the
paragraph
function changeText() {
// Use the getElementById() method to select the
paragraph element
var myParagraph =
document.getElementById("my-paragraph");
Page 128
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<p id="my-paragraph">Hello, world!</p>
<button onclick="changeText()">Change Text</button>
Page 129
<script>
function changeText() {
var paragraph =
document.getElementById("my-paragraph");
paragraph.textContent = "Goodbye, world!";
}
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<div id="my-div">
<p>Hello, world!</p>
</div>
<button onclick="changeHTML()">Change HTML</button>
<script>
function changeHTML() {
var div = document.getElementById("my-div");
div.innerHTML = "<p>Goodbye, world!</p>";
}
Page 130
</script>
</body>
</html>
Modifying Attributes
You can also modify the attributes of an element using
JavaScript. You can use the getAttribute() method to get the
value of an attribute, and the setAttribute() method to set the
value of an attribute. Let’s look at an example:
<!DOCTYPE html>
<html>
<body>
<img id="my-image" src="cat.jpg" alt="A cute cat">
<button onclick="changeImage()">Change
Image</button>
<script>
function changeImage() {
var image =
document.getElementById("my-image");
image.setAttribute("src", "dog.jpg");
image.setAttribute("alt", "A cute dog");
}
</script>
</body>
Page 131
</html>
Modifying CSS
CSS is used to style HTML elements and make them look
beautiful. JavaScript can be used to dynamically modify the
CSS styles applied to elements in the DOM.
<!DOCTYPE html>
<html>
<head>
<style>
p {
color: red;
}
Page 132
</style>
</head>
<body>
<p id="myParagraph">This is a paragraph.</p>
<button onclick="changeColor()">Change
color</button>
<script>
function changeColor() {
var p = document.getElementById("myParagraph");
p.style.color = "blue";
}
</script>
</body>
</html>
Modifying classes
Another way to modify CSS is to add or remove classes from
elements in the DOM. A class is a collection of CSS properties
that can be applied to multiple elements. By adding or
removing classes from elements, you can apply or remove
specific styles to those elements.
<!DOCTYPE html>
<html>
<head>
<style>
.blue {
Page 133
color: blue;
}
.underline {
text-decoration: underline;
}
</style>
</head>
<body>
<p id="myParagraph">This is a paragraph.</p>
<button onclick="addStyles()">Add styles</button>
<button onclick="removeStyles()">Remove
styles</button>
<script>
function addStyles() {
var p = document.getElementById("myParagraph");
p.classList.add("blue");
p.classList.add("underline");
}
function removeStyles() {
var p = document.getElementById("myParagraph");
p.classList.remove("blue");
p.classList.remove("underline");
}
</script>
</body>
</html>
In this example, two classes are defined in the CSS: "blue" and
"underline". When the "Add styles" button is clicked, both
classes are added to the paragraph element, applying the
styles defined in those classes. When the "Remove styles"
button is clicked, both classes are removed from the paragraph
element, removing the styles defined in those classes.
Page 134
Responding to events
The web is an interactive space, and users expect that their
actions will have consequences. That's where event handling
comes into play. In this section, we'll explore how to listen for
events and respond to them using JavaScript.
Event Listeners
In JavaScript, we can add an event listener to an HTML element
to listen for a specific event (such as a mouse click, keypress, or
page load) and trigger a function when the event occurs. The
basic syntax for adding an event listener is:
Event Handling
When an event is triggered, the function that we assigned to
the event listener will be executed. This function is called an
event handler. In the event handler, we can perform any action
that we want, such as changing the text of an element, hiding
an element, or showing a popup message.
element.addEventListener('click', function() {
// Do something when the element is clicked
});
Page 135
In the above example, we're adding an event listener to an
HTML element (which we'll refer to as element). We're listening
for the "click" event, and when that event occurs, we're
executing an anonymous function that performs some action.
Event Propagation
Events in JavaScript propagate from the top of the DOM tree to
the bottom. This means that when an event is triggered on an
element, it will first be handled by that element, then by its
parent element, and so on, until it reaches the top of the tree
(which is usually the window object).
element.addEventListener('click', function(event) {
event.stopPropagation();
// Do something when the element is clicked
});
Page 136
then passed to the callback function that is triggered by the
event.
Page 137
The Event Object Applied
In the previous section, we learned about the event object and
how it can be used to access information about the event that
was triggered. Let's apply this knowledge to an example where
multiple elements use the same event listener callback
function, and the event.target property is used to determine
which element was clicked.
HTML
<button id="button1">Button 1</button>
<button id="button2">Button 2</button>
<button id="button3">Button 3</button>
JavaScript
function changeTextColor(event) {
const targetButton = event.target;
if (event.shiftKey) {
targetButton.style.color = "blue";
} else {
targetButton.style.color = "red";
}
}
button1.addEventListener("click", changeTextColor);
Page 138
button2.addEventListener("click", changeTextColor);
button3.addEventListener("click", changeTextColor);
Code Exercises
Exercise 8.1: Accessing and Modifying DOM Elements
Create a HTML page that contains a heading, paragraph and
button elements. Use JavaScript to access each element by its
ID and modify its text content. When the button is clicked,
change the text content of the heading and paragraph to
something else.
Requirements:
● Create an HTML file with a heading, paragraph, and
button element
Page 139
● Add IDs to the heading, paragraph, and button
elements
● Use JavaScript to access each element by its ID and
modify its text content
● Add an event listener to the button element so that it
changes the text content of the heading and paragraph
when clicked
Requirements:
● Create an HTML file with a button element
● Add an ID to the button element
● Use JavaScript to add an event listener to the button
element
● When the button is clicked, change the background
color of the page using CSS
Requirements:
● Create an HTML file with a button element
● Add an ID to the button element
● Use JavaScript to add event listeners to the button
element for "mouseover" and "mouseout" events
● When the mouse is over the button, change its text
content
● When the mouse leaves the button, change its text
content back to its original text
Page 140
Exercise 8.4: Responding to Keyboard Events
Create a HTML page that contains a text input element. Use
JavaScript to change the text content of a paragraph element
when a key is pressed in the text input.
Requirements:
● Create an HTML file with a text input element and a
paragraph element
● Add IDs to the text input and paragraph elements
● Use JavaScript to add an event listener to the text input
element for "keydown" events
● When a key is pressed in the text input, change the text
content of the paragraph element to the value of the
text input
Requirements:
● Create an HTML file with an image element and a
button element
● Add an ID to the image and button elements
● Use JavaScript to add an event listener to the button
element
● When the button is clicked, change the source attribute
of the image to a new image URL
Requirements:
● Create an HTML file with a button element
Page 141
● Add an ID to the button element
● Use JavaScript to add an event listener to the button
element
● When the button is clicked, create a new paragraph
element with some text content and add it to the page
● When the button is clicked again, remove the
paragraph element from the page
Page 142
Bonus: Add a "submit" button that only becomes active once
all fields pass validation. When the user clicks the submit
button, display a message thanking them for their submission.
Critical Points
Introduction to the DOM:
● The DOM is a hierarchical representation of an HTML
document that allows for dynamic changes to web
pages through JavaScript.
● JavaScript can be used to access and modify DOM
elements, including their content and style.
Page 143
Accessing DOM Elements:
● The most common way to access a DOM element is by
its ID using document.getElementById().
● There are other ways to access DOM elements, such as
by their class name, tag name, or relationship to other
elements.
● It's important to use the correct syntax when accessing
elements to avoid errors.
Modifying CSS:
● JavaScript can be used to modify CSS properties of
DOM elements.
● Styles can be modified by changing the value of the
style property or by modifying individual CSS properties
using the element's style object.
● It's important to be careful when modifying CSS, as it
can affect the layout and functionality of a web page
.
Responding to Events:
● JavaScript can be used to respond to user interactions,
such as clicks, mouse movements, and key presses.
● Event listeners are used to trigger JavaScript functions
in response to specific events.
● Events can be handled with callback functions that are
executed when the event occurs.
Page 144
● The event object contains information about the event
that was triggered, such as the type of event, the target
element, and any additional data.
● The event object can be used to access and modify
DOM elements in response to events.
● Event propagation and delegation can be used to
handle events efficiently and minimize the number of
event listeners needed.
The FAQ
Q: What is the DOM?
A: The Document Object Model (DOM) is a programming
interface for web documents. It represents the page so that
programs can change the document structure, style, and
content.
Page 145
Q: What is the event object?
A: The event object is a JavaScript object that contains
information about the event that has occurred, such as the
target element and the type of event.
Page 146
Section 9: Asynchronous
JavaScript
Up until now, we've been focusing on synchronous code - that
is, code that runs one line at a time in the order that it's written.
However, in the real world of web development, we often need
to work with asynchronous code - code that runs out of order
or at a later time, such as when we're waiting for data to be
fetched from a server.
Callback functions
In JavaScript, a callback function is a function that is passed as
an argument to another function and is called inside that
function. Callback functions are commonly used in
asynchronous programming to handle events that take time to
complete, such as network requests or file input/output.
Page 147
Callback functions can be a bit tricky to work with, as they
often require nesting and can lead to what is known as
"callback hell." However, with proper coding practices and the
use of other asynchronous techniques like Promises and
async/await, callback functions can be a powerful tool for
building efficient and scalable applications.
function logSum(sum) {
console.log(`The sum is ${sum}.`);
}
Nested Callbacks
One of the biggest challenges with callback functions is
dealing with nested callbacks. This is when a function that
takes a callback function as an argument is itself passed as an
argument to another function that also takes a callback
Page 148
function as an argument. This can quickly lead to nested
functions that are difficult to read and maintain.
function displayData(data) {
// Simulate another network request that takes 1
second to complete
setTimeout(() => {
console.log(`Name: ${data.name}, Age:
${data.age}`);
}, 1000);
}
getData(displayData);
// Output after 3 seconds: Name: John, Age: 30
As you can see, this code can quickly become hard to read and
maintain. To avoid this, you can use other asynchronous
techniques like Promises or async/await, which we will cover in
the next sections.
Page 149
Promises
Promises are a powerful tool for handling asynchronous
JavaScript. They provide a way to work with asynchronous
operations in a more structured and predictable way. In this
section, we'll cover the basics of promises and how to use them
in your code.
Introduction to Promises
A promise is an object that represents a value that may not be
available yet, but will be at some point in the future. It is a
placeholder for a value that will be resolved eventually.
Promises provide a way to handle asynchronous code in a
more elegant way. They make it easier to manage and chain
together multiple asynchronous operations.
Creating a Promise
A promise is created using the Promise constructor function.
The constructor function takes a single argument, a callback
function, which takes two arguments: resolve and reject. The
resolve function is called when the promise is successfully
fulfilled, and the reject function is called when the promise is
rejected.
Page 150
Consuming a Promise
Once a promise is created, you can consume its result using
the then() method. The then() method takes two functions as
arguments: a success handler and an error handler. The
success handler is called when the promise is fulfilled, and the
error handler is called when the promise is rejected.
promise.then(
(result) => {
console.log(result);
},
(error) => {
console.log(error);
}
);
Chaining Promises
One of the most powerful features of promises is the ability to
chain them together. This allows you to execute multiple
asynchronous operations in sequence, without having to nest
callbacks.
Page 151
promise1
.then((result) => {
return promise2(result);
})
.then((result) => {
console.log(result);
});
In this example, we create two promises. The first one waits for
1 second and resolves with the string "Hello". The second
promise takes a parameter, appends " World" to it, and resolves
with the new string. We then chain the promises together
using the then() method. The first promise resolves with "Hello",
which is passed as a parameter to the second promise. The
second promise appends " World" to it and resolves with "Hello
World", which is finally printed to the console.
promise.then((result) => {
Page 152
console.log(result);
}).catch((error) => {
console.log(error);
});
Async/await
Asynchronous code can be hard to read and maintain due to
its nested and sometimes convoluted structure. Fortunately,
ES2017 introduced a new syntax called async/await that
simplifies the writing of asynchronous code. It allows you to
write asynchronous code in a way that looks and behaves like
synchronous code, making it easier to read, write, and debug.
What is Async/Await?
Async/await is a syntactic sugar built on top of Promises that
allows you to write asynchronous code using a more familiar
syntax. It allows you to write asynchronous functions that look
and behave like synchronous functions. Async/await is built on
top of Promises, so it is important to understand Promises
before diving into async/await.
Async Functions
Async functions are functions that return a Promise. They are
declared using the async keyword before the function
declaration. Async functions can contain one or more await
expressions, which pause the execution of the function until
the Promise is resolved or rejected.
Page 153
async function fetchData() {
const response = await
fetch('https://jsonplaceholder.typicode.com/todos/1');
const data = await response.json();
return data;
}
Error Handling
One of the benefits of using async/await is that it simplifies
error handling in asynchronous code. You can use try/catch
blocks to catch any errors that occur in the Promise chain. Here
is an example:
Page 154
Using Async/Await with Promise.all
Async/await can also be used with Promise.all to execute
multiple Promises in parallel. The Promise.all method takes an
array of Promises and returns a Promise that resolves to an
array of resolved values from the input Promises. Here is an
example:
Page 155
Note: We’re using the Open Weather Map API for the next
series of examples. You may need to obtain your own key and
insert it into the code where indicated. You can obtain your API
key at https://openweathermap.org/api.
fetch('https://api.openweathermap.org/data/2.5/weather?
q=Seattle&appid=YOUR_APP_ID')
.then(response => response.json())
.then(data => console.log(data));
fetch('https://api.openweathermap.org/data/2.5/weather?
q=Seattle&appid=YOUR_APP_ID')
.then(response => {
Page 156
if (!response.ok) {
throw new Error(response.status);
}
return response.json();
})
.then(data => console.log(data))
.catch(error => console.error(error));
getWeather('Seattle')
.then(data => console.log(data))
.catch(error => console.error(error));
Page 157
In this example, we've defined an async function called
getWeather that takes a city parameter. Inside the function, we
use await to wait for the response from fetch, and then check if
it was successful.
fetch(`https://www.goodreads.com/book/show/${bookId}.xm
l?key=${API_KEY}`)
.then(response => response.text())
Page 158
.then(data => {
const parser = new DOMParser();
const xml = parser.parseFromString(data,
'application/xml');
console.log(xml);
})
.catch(error => console.error(error));
Page 159
parsing large XML documents, so for more complex scenarios,
it may be necessary to use a more specialized XML parsing
library.
fetch(`https://api.openweathermap.org/data/2.5/weather?q=Lo
ndon&appid=${apiKey}`)
.then(response => response.json())
.then(data => console.log(data));
Once you have the weather data as a JavaScript object, you can
manipulate it and use it in your web application as needed. For
example, you could display the current temperature or weather
Page 160
conditions on your website. JSON data is commonly used with
APIs, so it's important to know how to parse it in JavaScript.
Code Exercise
Requirements:
Bonus:
1. Add error handling to your code to display a message if
the API request fails.
2. Add a loading spinner or animation to the div element
while the API request is being made.
3. Add a refresh button that retrieves a new randomly
generated user and displays their information.
Page 161
Note: You will need to obtain an API key from the Random User
API website (https://randomuser.me/) to make requests to the
API.
Critical Points
Callback functions:
● Callback functions are functions that are passed as
arguments to other functions.
● They are commonly used in asynchronous JavaScript to
handle data once it is retrieved.
● They allow you to execute code after a task has
completed, without blocking the main thread.
Promises:
● Promises are a way to handle asynchronous code that is
easier to read and write than callbacks.
● They represent a value that may not be available yet,
but will be resolved at some point in the future.
● They have a then() method that allows you to chain
together multiple asynchronous operations.
Async/Await:
● Async/await is a way to write asynchronous code that
looks more like synchronous code.
● It uses the async keyword to indicate that a function is
asynchronous, and the await keyword to pause the
function until a promise is resolved.
● It makes asynchronous code easier to read and write
than callbacks and promises.
Page 162
● It returns a promise that resolves with the response
from the server.
The FAQ
Q: What are callback functions in JavaScript?
A: A callback function is a function that is passed as an
argument to another function and is called when the first
function completes its task. In the context of asynchronous
JavaScript, callback functions are often used to handle the
results of asynchronous operations.
Page 163
A: JSON (JavaScript Object Notation) is a lightweight data
format that is commonly used for transmitting data between a
server and a web application. APIs often return data in the
form of JSON, which can be parsed and used by JavaScript
code to update the content of a web page dynamically.
Page 164
Section 10: JavaScript Tools and
Libraries
In this section, we will explore some of the most popular tools
and libraries used by JavaScript developers to simplify their
workflow and enhance their applications. We will begin by
discussing Node.js and npm, which are essential for server-side
JavaScript development and managing dependencies. We will
also cover Webpack and Babel, which are powerful tools for
bundling and transpiling JavaScript code, respectively.
Page 165
Installing Node.js and NPM
To get started with Node.js and NPM, you'll need to install
them on your computer. The easiest way to do this is by
downloading and installing the Node.js installer from the
official website. Once installed, you can use the node
command to run JavaScript code from the command line, and
the npm command to manage packages.
Page 166
')
.then(response => {
console.log(response.data);
})
.catch(error => {
console.log(error);
});
Page 167
Installing Webpack and Babel
Before we can use Webpack and Babel, we need to install
them. We can do this easily using NPM, the Node.js package
manager.
First, let's install Webpack and its command line interface (CLI)
globally:
First, we'll create a new file in the root of our project called
webpack.config.js. This file will contain our Webpack
configuration. Here's a basic example:
module.exports = {
entry: './src/index.js',
output: {
filename: 'main.js',
path: path.resolve(__dirname, 'dist')
},
Page 168
module: {
rules: [
{
test: /\.js$/,
exclude: /(node_modules)/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env']
}
}
}
]
}
};
Introduction to React
Page 169
extension that allows us to write HTML-like syntax in our
JavaScript code.
// using React.createElement()
const element = React.createElement('h1', null, 'Hello,
world!');
ReactDOM.render(element,
document.getElementById('root'));
// using JSX
const element = <h1>Hello, world!</h1>;
ReactDOM.render(element,
document.getElementById('root'));
Rendering a Component
To render a component, we use the ReactDOM.render()
function. This function takes a component and a DOM element
as arguments and renders the component inside the DOM
element.
function App() {
return (
<div>
<h1>Hello, world!</h1>
<p>Welcome to my React app.</p>
</div>
);
}
ReactDOM.render(<App />,
document.getElementById('root'));
Page 170
Handling Events
React allows us to handle events in a declarative way using
props. We can define event handlers as methods on our
component and pass them as props to child components.
function Button(props) {
return (
<button onClick={props.onClick}>
{props.label}
</button>
);
}
render() {
return (
<div>
<h1>Hello, world!</h1>
<Button label="Click me"
onClick={this.handleClick} />
</div>
);
}
}
ReactDOM.render(<App />,
document.getElementById('root'));
Page 171
Express and other back-end frameworks
In web development, the back-end refers to the server-side of
an application, responsible for processing data and returning it
to the client-side. One of the most popular back-end
frameworks for Node.js is Express. However, there are also other
great options to choose from, such as Koa and Hapi.
Installing Express
To get started with Express, you first need to install it through
npm, the package manager for Node.js. Open a terminal
window and run the following command:
This command will install the latest version of Express and its
dependencies. You can also specify a specific version of Express
by adding @version_number to the end of the command.
app.listen(3000, () => {
console.log('Server started on port 3000');
});
Page 172
In this example, we require the Express module and create a
new app instance. We then define a route for the root path '/'
using the app.get() method, which takes a callback function
with two parameters, req for the request and res for the
response. Finally, we start the server on port 3000 using the
app.listen() method and log a message to the console.
Page 173
Using Other Back-end Frameworks
While Express is a popular choice for Node.js back-end
development, there are also other great options to choose
from. For example, Koa is a more lightweight alternative to
Express, focusing on a middleware-based approach. Hapi is
another option, providing a more structured and modular
approach to building back-end applications.
Jest provides a simple and intuitive API for writing tests. Here's
an example of a test that checks if a function returns the
correct value:
function add(a, b) {
return a + b;
}
Page 174
test('adds two numbers', () => {
expect(add(1, 2)).toBe(3);
});
function multiply(a, b) {
return a * b;
}
describe('multiply', () => {
it('should return the product of two numbers', () =>
{
assert.equal(multiply(2, 3), 6);
});
});
Page 175
Code Coverage
// .babelrc
{
"plugins": ["istanbul"]
}
// package.json
{
"scripts": {
"test": "jest --coverage"
}
}
Page 176
Critical Points
Node.js and npm:
● Node.js is a JavaScript runtime built on Chrome's V8
engine.
● npm is the package manager for Node.js and is used to
install and manage dependencies.
● Node.js can be used for server-side development,
command-line tools, and build tools.
● The package.json file is used to manage project
dependencies and configuration.
Page 177
● Other back-end frameworks include Koa, Hapi, and
Nest.
● Back-end frameworks provide tools for handling
routing, middleware, and serving data to the front-end.
● The Model-View-Controller (MVC) pattern is often used
in back-end development.
The FAQ
Q: What is Node.js, and why is it important?
A: Node.js is a JavaScript runtime built on the Chrome V8
engine. It allows developers to run JavaScript on the
server-side, which means they can use the same language on
both the client and server. Node.js also includes a built-in
package manager called npm, which makes it easy to manage
dependencies and share code with other developers.
Q: What are Webpack and Babel, and how are they used in
JavaScript development?
A: Webpack is a module bundler that allows developers to
organize and package their code for deployment to a
production environment. Babel is a JavaScript compiler that
allows developers to use the latest language features, even if
they aren't supported by all browsers. Together, Webpack and
Page 178
Babel make it easier to write and deploy complex JavaScript
applications.
Q: What are testing frameworks like Jest and Mocha, and why
are they important?
A: Testing frameworks like Jest and Mocha provide a way for
developers to write automated tests for their code. These tests
can help ensure that code is working correctly, even as it is
updated or modified. Testing frameworks also make it easier to
catch and fix bugs before they make it to production, which
can save time and improve the overall quality of an application.
Page 179
Section 11: JavaScript Projects
Congratulations on making it to the end of the JavaScript
Workbook! By now, you should have a solid understanding of
the fundamentals of JavaScript, from variables and data types
to functions and objects. But what comes next? Where do you
go from here?
That's where the project section comes in. In this section, we'll
be providing you with a number of suggested projects that you
can work on to solidify your knowledge and take your
JavaScript skills to the next level. These projects will range from
small, bite-sized exercises to larger, more complex projects that
will challenge you and push you to grow as a developer.
Page 180
● Use a weather API such as OpenWeatherMap or
Weather Underground
● Allow users to input a location and retrieve weather
data
● Display the current temperature, humidity, and wind
speed
● Style the app using CSS
Resources:
OpenWeatherMap API: https://openweathermap.org/api
Weather Underground API:
https://www.wunderground.com/weather/api
Project: To Do List
Description: Create a simple todo list app that allows users to
add and remove items. The app should display a list of all items
and allow users to mark items as complete.
Requirements:
● Allow users to add new items to the todo list
● Allow users to remove items from the todo list
● Allow users to mark items as complete
● Display a list of all items
Resources:
localStorage API:
https://developer.mozilla.org/en-US/docs/Web/API/Window/loc
alStorage
Project: Calculator
Description: Create a basic calculator app that allows users to
perform basic arithmetic operations.
Requirements:
Page 181
● Display a basic calculator interface with buttons for
numbers and operations
● Allow users to perform addition, subtraction,
multiplication, and division
● Display the result of each calculation
Requirements:
● Use a quote API such as Quotes REST API or forismatic
API
● Display a random quote each time the user refreshes
the page
● Allow users to share the quote on social media
Resources:
● Quotes REST API: https://quotes.rest/
● forismatic API: https://forismatic.com/en/api/
Requirements:
● Display a grid of cards with hidden images
● Allow users to click on cards to reveal their images
● Keep track of which cards have been revealed
● Allow users to match pairs of cards
● Display a message when the game is over
Page 182
Project: Hangman
Description: Create a hangman game where users try to guess
a hidden word by guessing letters one at a time.
Requirements:
● Display a series of blanks representing the hidden word
● Allow users to guess letters one at a time
● Keep track of which letters have been guessed
● Display the guessed letters and the blanks for the
hidden word
● Display a message when the game is over
Requirements:
● Use an API to retrieve recipe data
● Allow users to search for recipes based on keywords or
ingredients
● Display recipe details including ingredients,
instructions, and nutritional information
● Allow users to save and organize their favorite recipes
● Use CSS to style the app
Page 183
Project: BART Transit Tracker
Description:
Create a real-time transit tracker that allows users to check the
location of BART trains in the San Francisco Bay Area.
Requirements:
● Display a map of the BART system
● Allow users to select a station to view real-time
departures and arrivals
● Display the next few trains departing and arriving at the
selected station, including their estimated arrival times
● Highlight the selected station on the map
● Update train locations and estimated arrival times in
real-time
● Allow users to filter train arrivals and departures by
destination, line, and direction
● Provide clear instructions for using the app
Resources:
● BART API documentation:
https://api.bart.gov/docs/overview/index.aspx
● Mapbox API for displaying the map:
https://www.mapbox.com/
● jQuery or another JavaScript library for making API calls
and updating the UI in real-time
● Bootstrap or another CSS framework for styling the app
Note: You will need to obtain an API key from BART to use their
API.
Page 184
landmarks. The application should provide information about
each place of interest, such as hours of operation, reviews,
photos, and directions.
Requirements:
Resources:
● Google Maps API, Mapbox API, or OpenStreetMap API
● HTML and CSS for layout and styling
● JavaScript for dynamic functionality
● A backend database (e.g. Firebase or MongoDB) to store
user data and reviews
● Bootstrap or another front-end framework for
responsive design
Page 185
Excerise Soutions
Exercise 1.1: Simple variable manipulation
let x = 10;
let y = 5;
console.log(x + y); // 15
console.log(x - y); // 5
console.log(x * y); // 50
console.log(x / y); // 2
let a = 10;
let b = 5;
console.log(a > b); // true
console.log(a <= b); // false
console.log(a === b); // false
console.log(a !== b); // true
let x = true;
let y = false;
console.log(x && y); // false
console.log(x || y); // true
console.log(!x); // false
Page 186
Exercise 1.5: Function creation
console.log(myString);
console.log(myNumber);
console.log(myBoolean);
console.log(myArray);
console.log(myObject);
Page 187
Exercise 2.4: Converting a String to a Number
let stringNumber = '7';
let numberValue = Number(stringNumber);
console.log(numberValue + 5);
myArray.push(4);
myArray.shift();
console.log(myArray);
console.log(myBoolean);
console.log(stringBoolean);
console.log(myObject.hobbies[1]);
console.log(myObject);
Page 188
let number = prompt("Enter a number:");
if (number % 2 === 0) {
console.log("The number is even.");
} else {
console.log("The number is odd.");
}
Page 189
while (num !== 7) {
num = Math.floor(Math.random() * 10) + 1;
console.log(num);
}
console.log(num);
Page 190
for (let i = 0; i < numbers.length; i++) {
const number = numbers[i];
if (number < 0) {
continue;
}
console.log(number);
}
Page 191
}
Page 192
Function A
const multiplyByTwo = (num) => num * 2;
Function B
const addNumbers = (num1, num2) => num1 + num2;
Function C
const greeting = (name) => {
return "Hello, " + name + "!";
}
or
const greeting = (name) => `Hello, ${name}!`;
Page 193
for(let num of arr1) {
sum += num;
}
for(let num of arr2) {
sum += num;
}
return sum;
}
Page 194
myArray.push(4, 5);
Page 195
const numbers = [1, 2, 3, 4, 5];
Page 196
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Random Quote Generator</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container">
<h1>Random Quote Generator</h1>
<blockquote>
<p id="quote"></p>
</blockquote>
<button id="btn">Generate</button>
</div>
<script src="script.js"></script>
</body>
</html>
CSS:
.container {
max-width: 800px;
margin: 0 auto;
text-align: center;
}
blockquote {
font-size: 24px;
margin-bottom: 40px;
}
button {
padding: 10px 20px;
font-size: 20px;
border: none;
background-color: #007bff;
color: white;
Page 197
cursor: pointer;
}
JavaScript
const quotes = [
"The best way to predict the future is to invent it.
- Alan Kay",
"The only way to do great work is to love what you
do. - Steve Jobs",
"If you want to achieve greatness, stop asking for
permission. - Unknown",
"It does not matter how slowly you go as long as you
do not stop. - Confucius",
"Success is not final, failure is not fatal: It is
the courage to continue that counts. - Winston
Churchill",
"Believe you can and you're halfway there. - Theodore
Roosevelt",
"Don't watch the clock; do what it does. Keep going.
- Sam Levenson",
"You are never too old to set another goal or to
dream a new dream. - C.S. Lewis",
"If you can dream it, you can do it. - Walt Disney",
"The only person you are destined to become is the
person you decide to be. - Ralph Waldo Emerson"
];
function generateQuote() {
const randomIndex = Math.floor(Math.random() *
quotes.length);
quoteElem.textContent = quotes[randomIndex];
}
btn.addEventListener("click", generateQuote);
Page 198
Exercise 6.1: Creating a Class
// Define a class called Person with properties 'name'
and 'age'
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
}
makeSound() {
console.log(`${this.species} makes a ${this.sound}
sound.`);
Page 199
}
}
wagTail() {
console.log(`${this.name} wags its tail.`);
}
}
purr() {
console.log(`${this.name} purrs.`);
}
}
Page 200
No solution Set
try {
console.log(divide(10, 2));
} catch (error) {
console.log("Error:", error.message);
} finally {
console.log("Function call finished.");
}
try {
console.log(divide(10, 0));
} catch (error) {
console.log("Error:", error.message);
} finally {
console.log("Function call finished.");
}
try {
console.log(divide("abc", 2));
} catch (error) {
console.log("Error:", error.message);
} finally {
console.log("Function call finished.");
}
Page 201
Exercise 8.1: Accessing and Modifying DOM Elements
HTML
<!DOCTYPE html>
<html>
<head>
<title>Exercise 8.1</title>
</head>
<body>
<h1 id="heading">This is a heading</h1>
<p id="paragraph">This is a paragraph</p>
<button id="button">Click me</button>
<script src="script.js"></script>
</body>
</html>
JavaScript
const heading = document.getElementById('heading');
const paragraph = document.getElementById('paragraph');
const button = document.getElementById('button');
button.addEventListener('click', function() {
heading.textContent = 'New Heading';
paragraph.textContent = 'New Paragraph';
});
Page 202
</head>
<body>
<button id="button">Click me</button>
<script src="script.js"></script>
</body>
</html>
JavaScript
const button = document.getElementById('button');
button.addEventListener('click', function() {
document.body.style.backgroundColor = 'red';
});
<!DOCTYPE html>
<html>
<head>
<title>Exercise 8.3</title>
</head>
<body>
<button id="button">Mouse Over Me</button>
<script src="script.js"></script>
</body>
</html>
JavaScript
const button = document.getElementById('button');
button.addEventListener('mouseover', function() {
button.textContent = 'Mouse is over me';
});
Page 203
button.addEventListener('mouseout', function() {
button.textContent = 'Mouse over me';
});
JavaScript
const textInput = document.getElementById('textInput');
const output = document.getElementById('output');
textInput.addEventListener('keydown', function(event) {
output.textContent = event.key;
});
Page 204
<body>
<img id="image"
src="https://www.w3schools.com/html/pic_trulli.jpg">
<button id="button">Change Image</button>
<script src="script.js"></script>
</body>
</html>
JavaScript
const image = document.getElementById('image');
const button = document.getElementById('button');
button.addEventListener('click', function() {
image.setAttribute('src',
'https://www.w3schools.com/html/pic_bulbo.jpg');
});
JavaScript
const toggleBtn = document.querySelector('#toggleBtn');
const paragraphContainer =
document.querySelector('#paragraphContainer');
Page 205
let paragraph = null;
let paragraphVisible = false;
toggleBtn.addEventListener('click', () => {
if (!paragraphVisible) {
paragraph = document.createElement('p');
paragraph.textContent = 'This paragraph was created
dynamically!';
paragraphContainer.appendChild(paragraph);
paragraphVisible = true;
} else {
paragraphContainer.removeChild(paragraph);
paragraphVisible = false;
}
});
JavaScript
const list = document.getElementById("myList");
list.addEventListener("click", function(event) {
if (event.target.nodeName === "LI") {
event.target.style.color = "red";
}
});
Page 206
<form>
<label for="name">Name:</label>
<input type="text" id="name" name="name"><br><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email"><br><br>
<label for="phone">Phone:</label>
<input type="tel" id="phone" name="phone"><br><br>
<label for="password">Password:</label>
<input type="password" id="password"
name="password"><br><br>
<div id="message"></div>
JavaScript
// Get form elements
const nameInput = document.getElementById("name");
const emailInput = document.getElementById("email");
const phoneInput = document.getElementById("phone");
const passwordInput =
document.getElementById("password");
const submitBtn = document.getElementById("submit");
Page 207
const name = nameInput.value.trim();
if (name === "") {
showError(nameInput, "Name is required");
} else if (!isValidName(name)) {
showError(nameInput, "Name can only contain letters
and spaces");
} else {
showSuccess(nameInput);
}
}
Page 208
const password = passwordInput.value.trim();
if (password === "") {
showError(passwordInput, "Password is required");
} else if (!isValidPassword(password)) {
showError(
passwordInput,
"Password must be at least 8 characters long and
contain at least one uppercase letter, one lowercase
letter, and one number"
);
} else {
showSuccess(passwordInput);
}
}
Page 209
return regex.test(password);
}
Page 210
<div id="counterDisplay">0</div>
JavaScript
const counterBtn =
document.getElementById('counterBtn');
const counterDisplay =
document.getElementById('counterDisplay');
let count = 0;
counterBtn.addEventListener('click', function(event) {
count++;
counterDisplay.innerHTML = count;
});
Page 211
src="https://via.placeholder.com/200x200" alt="Image
3">
<script src="script.js"></script>
</body>
</html>
JavaScript
const images = document.querySelectorAll("img");
Page 212
}
</style>
</head>
<body>
<button id="get-user-btn">Get Random User</button>
<div id="user-container"></div>
<script src="script.js"></script>
</body>
</html>
JavaScript
const userContainer =
document.querySelector('#user-container');
const getUserBtn =
document.querySelector('#get-user-btn');
getUserBtn.addEventListener('click', getUser);
function getUser() {
userContainer.innerHTML = ''; // clear previous user
data
userContainer.classList.add('loading'); // add
loading class to div element
fetch('https://randomuser.me/api/')
.then(response => response.json())
.then(data => {
const user = data.results[0];
const userImg = document.createElement('img');
userImg.src = user.picture.large;
userContainer.appendChild(userImg);
const userName = document.createElement('p');
userName.textContent = `${user.name.title}
${user.name.first} ${user.name.last}`;
userContainer.appendChild(userName);
const userLocation = document.createElement('p');
userLocation.textContent =
`${user.location.city}, ${user.location.state},
Page 213
${user.location.country}`;
userContainer.appendChild(userLocation);
userContainer.classList.remove('loading'); //
remove loading class when data is displayed
})
.catch(error => {
console.error('Error:', error);
userContainer.textContent = 'Failed to retrieve
user data. Please try again.';
userContainer.classList.remove('loading'); //
remove loading class when error message is displayed
});
}
CSS
.loading {
background-image: url('loading.gif');
background-size: 50px 50px;
background-repeat: no-repeat;
background-position: center;
}
Page 214
About the Author
Mark Lassoff has taught over 2.5 million people coding and
digital design through online courses, in corporate classrooms
and in technical workshops.
Mark has won multiple awards for his courses and teaching.
Mark’s clients have included Lockheed Martin, Blue Cross/Blue
Shield and Apple. When not teaching, Mark enjoys dining out,
travel, and time with friends and family.
Learn Skills That Will Benefit You for The Rest of Your Life
Testimonials
"This is a great course it's very beginner friendly love the
assignments but to be honest they can feel a bit lengthy
I love the small in between humors from Mark
Thanks for this amazing course looking forward to learning
more from this course " - Nabeel Wasif
“… The videos were very thorough but the best are the exercises
that you must complete. Like Mark says, writing code is not a
spectator sport" - Dan Dlhy