[FREE PDF sample] (Ebook) How JavaScript Works: Master the Basics of JavaScript and Modern Web App Development by Jonathon Simpson ISBN 9781484297377, 1484297377 ebooks
[FREE PDF sample] (Ebook) How JavaScript Works: Master the Basics of JavaScript and Modern Web App Development by Jonathon Simpson ISBN 9781484297377, 1484297377 ebooks
com
https://ebooknice.com/product/how-javascript-works-master-
the-basics-of-javascript-and-modern-web-app-
development-54544624
OR CLICK HERE
DOWLOAD EBOOK
ebooknice.com
ebooknice.com
ebooknice.com
ebooknice.com
(Ebook) JavaScript for Web Developers: Understanding the
Basics by Mark Simon ISBN 9781484297735, 1484297733
https://ebooknice.com/product/javascript-for-web-developers-
understanding-the-basics-53488768
ebooknice.com
ebooknice.com
ebooknice.com
ebooknice.com
How JavaScript
Works
Master the Basics of JavaScript and
Modern Web App Development
—
Jonathon Simpson
How JavaScript Works
Master the Basics of JavaScript
and Modern Web App
Development
Jonathon Simpson
How JavaScript Works: Master the Basics of JavaScript and Modern Web
App Development
Jonathon Simpson
Belfast, Antrim, UK
Introduction����������������������������������������������������������������������������������������xv
iii
Table of Contents
Assignment Operators����������������������������������������������������������������������������������������26
Variable Concatenation����������������������������������������������������������������������������������27
JavaScript Comments�����������������������������������������������������������������������������������������29
Logical Statements���������������������������������������������������������������������������������������������30
If…else Statements��������������������������������������������������������������������������������������30
Switch Statements����������������������������������������������������������������������������������������33
Block Scoping with Logical Statements��������������������������������������������������������36
Conditional Operator in Variables������������������������������������������������������������������38
Logical Statement Comparison Operators�����������������������������������������������������38
Logical Statement Logical Operators������������������������������������������������������������41
Summary������������������������������������������������������������������������������������������������������������42
iv
Table of Contents
v
Table of Contents
Chapter 7: Types�������������������������������������������������������������������������������131
Primitive Types��������������������������������������������������������������������������������������������������131
Primitive Wrappers��������������������������������������������������������������������������������������������133
Using Wrappers to Create Types�����������������������������������������������������������������������136
The Number Type and NaN�������������������������������������������������������������������������������137
Number Type Mathematics��������������������������������������������������������������������������139
Mathematical Methods��������������������������������������������������������������������������������141
The Date Type����������������������������������������������������������������������������������������������������143
The Symbol Type�����������������������������������������������������������������������������������������������147
Truthy and Falsy Types��������������������������������������������������������������������������������������149
vi
Table of Contents
vii
Table of Contents
viii
Table of Contents
ix
Table of Contents
Index�������������������������������������������������������������������������������������������������315
x
About the Author
Jonathon Simpson studied at UCL and currently works in product
development at Revolut, a global neobank and financial technology
company that offers banking services. He has over 15 years of web
development experience working on a wide range of products and
services. Jonathon also owns and operates a popular software engineering
blog focusing on JavaScript and web development.
xi
About the Technical Reviewer
Russ Ferguson is a web application developer living in Brooklyn, New York.
He has worked on projects for organizations such as Ann Taylor, MTV,
DC Comics, and LG. Currently, he is the Vice President at Bank of America
managing a team of Angular developers, building internal applications.
xiii
Introduction
JavaScript is one of the most used programming languages in the
world. When JavaScript was first created, it was a useful tool for adding
interactivity to web pages. Since then, it has evolved to power back-end
servers, massive front-end web applications, and even iPhone and Android
applications via tools like Electron and Tauri.
While JavaScript has matured as a language its complexity seems to
have increased. What started as simple scripts inside HTML tags now
seems to involve compile steps via TypeScript and frameworks like
React, Vue.js, or Svelte. For those getting started in JavaScript, it can be
overwhelming, even though these tools are just an additional level of
abstraction which ultimately compiles down into vanilla JavaScript.
In this book, we’ll learn how JavaScript works from the bottom up,
which will prepare you for everything web development and JavaScript-led
app development can throw at you. We’ll also explain some of the quirks
you’ll find in JavaScript and how many of them have come to be due to
JavaScript’s long and varied history.
After that, we’ll cover JavaScript’s unique approach to inheritance
before moving into more complicated topics like memory management,
classes, APIs, and web workers. We’ll explore how the weakly typed system
JavaScript employs has both benefits and downsides.
As a fundamental part of the web stack, and with more people using
it every day, there has never been a better time to learn JavaScript. This
book will guide you through everything you need to know, so that you can
master modern web app development.
xv
CHAPTER 1
Introduction
to JavaScript
JavaScript is a programming language that first appeared in 1995 as the
scripting language for the Netscape browser. Since then, it has evolved into
one of the most used programming languages in the world. While its initial
goal was to add interactivity to websites, it has since come to do just about
everything, including creating desktop apps and back-end APIs.
JavaScript is everywhere, and over the years, many frameworks have
been built on top of it, such as jQuery, React, Vue.js, and Svelte. All of
this can make learning JavaScript intimidating, as there are often many
different ways to achieve the same thing.
In this book, we’ll be covering how JavaScript works at a fundamental
level. That will then make it is easier to understand how frameworks
like React and Vue.js work. We’ll discuss why things work the way they
do in JavaScript and the various quirks that come with years of ongoing
development on the language.
JavaScript today broadly falls into two major categories:
JavaScript Fundamentals
JavaScript is based on a language standard called ECMAScript. How
JavaScript should exactly work is documented in a specific standard called
ECMA-262. Since ECMAScript does not provide any tools to compile
JavaScript, every implementation of JavaScript creates its own version
of JavaScript. That includes your browser and back-end compilers like
Node.js.
For the most part, these implementations follow ECMA-262, but
since each implementation is done by different teams, there can be some
minor discrepancies or different feature sets depending on the browser or
implementation.
In this chapter, we will be covering how you can set yourself up to start
using JavaScript, including how to set up JavaScript projects when using
Node.js. In future chapters, we will explore how to write JavaScript code.
2
Chapter 1 Introduction to JavaScript
You’ll see that no types are defined here. For example, we did not have
to mention that "Some String" was a String. JavaScript determines types
based on context – so it will take x to be a String simply because we put
its value in quotation marks. Similarly, it will dynamically interpret y as
being of type Number since it lacks quotation marks and z as being of type
Boolean since it has no quotation marks and uses the keyword false.
This makes JavaScript quite easy to pick up, but quite hard to master.
The lack of strong typing can mean that you unknowingly create bugs in
your software since JavaScript will not always throw errors if unexpected
types show up, and even worse, JavaScript may dynamically interpret types
incorrectly in some cases.
3
Chapter 1 Introduction to JavaScript
For more complex applications with lots of test cases, developers often
reach for TypeScript instead of JavaScript for this reason. TypeScript
is JavaScript, but extended. It’s strongly typed, meaning types must be
mentioned in your code.
4
Chapter 1 Introduction to JavaScript
Writing JavaScript
JavaScript on the front end is found inside HTML on web pages. As such,
familiarity with HTML is quite important when we work with JavaScript. To
create your first file containing JavaScript, you can start by making a .html
file. We usually call the home page of a website index.html when building
websites, so for this example, I created a new HTML file called index.html.
.html files can be opened by any web browser, such as Google
Chrome. You can edit your HTML file by opening it up in a text
or code editor (Notepad included), and puting in this standard
“boilerplate” HTML:
<!DOCTYPE html>
<html>
<head>
<title>My First JavaScript</title>
</head>
<body>
<p>Hello World</p>
5
Chapter 1 Introduction to JavaScript
<script type=”text/javascript”>
// This is JavaScript!
</script>
</body>
</html>
Note You can use any text editor (like Notepad) to create HTML
and even JavaScript. While that works fine, it’s better to use a
professional code editor instead. One of the most popular code
editors used in the software development community is VS Code.
You can download it via https://code.visualstudio.com/.
This will color code your JavaScript and give you a lot of other useful
features.
<script type="text/javascript">
// This is JavaScript!
</script>
Since JavaScript applications can get quite long, you may see this
<script> tag substituted out for a file instead. This can be useful since it
lets us separate our HTML and JavaScript into different files.
For example, if we had a separate JavaScript file called myScript.js
stored in the same folder as index.html file, we could load that into our
HTML document by using the src attribute on the script tag:
<script src="myScript.js"></script>
6
Chapter 1 Introduction to JavaScript
You may also see JavaScript embedded into HTML via the attributes
of HTML tags. For example, JavaScript can be put inside a button to cause
something to happen when a user clicks that button:
7
Chapter 1 Introduction to JavaScript
Figure 1-1. After you install VS Code, open the application. By going
to File ➤ Open Folder… or clicking “Open Folder” in VS Code and
finding your “My JavaScript” folder
8
Chapter 1 Introduction to JavaScript
9
Chapter 1 Introduction to JavaScript
Running the node command lets you compile and execute JavaScript
files. Let’s try it out – create a file called index.js in a code editor or
Notepad, and add the following JavaScript code before saving:
console.log("Hello World!")
Then you can execute this file by using the node command in terminal:
node index.js
This will produce an output which looks something like what is shown
in Figure 1-3.
10
Chapter 1 Introduction to JavaScript
Note If you saved your index.js file in another directory, you will
need to provide the full directory link. To navigate directories, use
the cd command. For example, if your index.js file was in “/Users/
JohnDoe/Documents/”, you would run cd /Users/JohnDoe/
Documents/ and only after that, run node index.js.
cd ~/Desktop/node-project
After that’s done, you can use the npm init command, which is
installed along with Node.js, to initiate your project. You can see how that
looks in Figure 1-4.
11
Chapter 1 Introduction to JavaScript
Figure 1-4. When using the npm init command, you will be asked to
enter some information about your new project as shown earlier
All you have to do now is type in answers to each question and press
enter. For example, the first question asks what you want to call your
project – so type in the name of your project, and press enter.
Your folder will now contain a package.json file summarizing the
information you provided. Since you’ve initialized your Node.js project,
you’ll now be able to run other commands like npm install now, which
lets you install third party dependencies.
JavaScript Support
Traditional software is usually written by a developer and downloaded
onto a user’s computer or device. This is the case with things like video
games, apps on your phone, or big applications like Adobe Photoshop.
When writing code in JavaScript, things are very different. The software
the user installs is the browser, not your website! The browser then loads
12
Chapter 1 Introduction to JavaScript
your web page within it. Since everyone has their own browser preference,
and not everyone keeps their browsers up to date, JavaScript that works in
one browser can oftentimes not work in another. For example, Firefox may
support a new JavaScript feature, but Chrome may not. The worst thing
about this is you can’t really use a new JavaScript feature on the front end
until a majority of browsers have implemented it.
If you are coming from other languages, then worrying about browser
support will be a foreign concept to you. In JavaScript, it is a real thing.
In recent times, since most browsers are “evergreen” (meaning they
auto-update), this has become less of a problem than it used to be, but
sometimes different browsers just disagree on what should and shouldn’t
be implemented. Promising new features may end up implemented in just
Chrome, just Safari, or just Firefox.
Throughout this book, we’ll only be looking at JavaScript with broad
browser support, meaning you don’t need to worry about if you can or
can’t use it. However, when you start exploring JavaScript in your own
time, and especially when looking at more advanced functionality, it’s
important to check if browsers support it. You can find good browser
support tables on websites like https://caniuse.com/ or https://
developer.mozilla.org/.
An example of a browser support table can be found in Figure 1-5, for
the GPU feature.
13
Chapter 1 Introduction to JavaScript
Figure 1-5. Not all browsers support every new JavaScript feature. In
the preceding example, only Chrome and Edge have support. Other
browsers only have partial support or none at all. That means if you
tried to implement this on a website, only some users could use it!
Summary
In this chapter, we’ve looked at how to set up your workspace to begin
writing code with JavaScript. We’ve discussed what JavaScript is typically
used for and some of the pitfalls or differences between it and other
languages. Now that we’ve covered the basics let’s look at how to write
JavaScript code.
14
CHAPTER 2
Getting Started
As we go through this chapter, it will be good to have a work space where
you can write and test your JavaScript. For these purposes, I’ve created a
folder called “javascript-project” in my documents folder. Within that, I
have created two files – index.html and index.js.
Since our focus will be writing JavaScript, your HTML file can be
relatively simple:
<!DOCTYPE html>
<html>
<head>
<title>My First JavaScript</title>
</head>
<body>
<p>Hello World</p>
<script src="index.js"></script>
</body>
</html>
Any JavaScript code you want to try out can be put in index.js. For
now, I’ve only put a simple console.log method:
console.log("Hello World!")
16
Chapter 2 Code Structure and Logical Statements
Semicolons
For readability, JavaScript is sometimes written with a semicolon at the
end of each line. For example:
console.log("Hello World!");
console.log("Goodbye World!");
However, this is not necessary, and it’s also just as common to see the
same code written without semicolons:
console.log("Hello World!")
console.log("Goodbye World!")
console.log(5 +
6)
For the code in this book, we will be omitting the semicolon unless it is
really needed.
17
Chapter 2 Code Structure and Logical Statements
Spacing
One of the most vigorously fought over code conventions is whether to use
tabs or spaces for indenting. While there is essentially no right or wrong
answer to this, it is important to be consistent. If you use tabs, then always
use tabs for indents and likewise for spaces.
Unlike Python, indents play no functional role in JavaScript, but they
do serve to make your code more readable when others look at it. While
it is certainly fine to use tabs, spaces are going to cause you less of a
headache. That’s because different ecosystems and operating systems can
be configured to handle tabs differently, whereas spaces are consistently
sized across all systems.
In this book, we will indent with four spaces. Here is an example of
how that will look:
let myVariable = 5
if(myVariable === 5) {
console.log("The variable is 5!")
}
Note If you use the tab key instead of spaces in VS Code to indent
your code, you can configure VS Code to automatically convert these
to spaces if you want it to. The configuration option is found by
opening any file and selecting the “Spaces/Tab Size” option in the
bottom right-hand corner.
18
Chapter 2 Code Structure and Logical Statements
When naming variables and functions, all of these are fine to use, but
again, it is important to be consistent. If you decide to use camel case, then
make sure you use it everywhere. For the purposes of this book, we will be
using camel case.
JavaScript Variables
As we begin writing JavaScript, the first thing you’re going to need to learn
about are variables. Variables are a way to assign a fixed name to a data
value. There are three ways to create a variable in JavaScript, using three
different keywords:
• var
• let
• const
19
Chapter 2 Code Structure and Logical Statements
let myVariable = 5
console.log(myVariable)
Note It may seem like we are putting data into the variable, but a
better way to think about it is we are making data and then pointing
the keyword “myVariable” at the data we just made.
It’s not possible to assign a variable with let twice. If you think of your
variable as pointing to some data, it’s easy to see why – the same variable
can’t point to two different pieces of data. For example, the following code
will produce the error, which is shown in Figure 2-2.
let myVariable = 5
let myVariable = 10
console.log(myVariable)
20
Chapter 2 Code Structure and Logical Statements
let myVariable = 5
myVariable = 10
console.log(myVariable)
It may seem like the data has changed (or “mutated”), but actually we’ve
just made new data somewhere and pointed our variable to that instead. The
data “5” still exists somewhere. It just has no variable pointing to it anymore.
When a piece of data is no longer referenced in our code, JavaScript may
remove it from memory using something called “garbage collection.” This
allows JavaScript to free up memory when data is no longer used.
let myVariable = 5
{
let myVariable = 10
console.log(myVariable)
}
console.log(myVariable)
21
Chapter 2 Code Structure and Logical Statements
Figure 2-3. While using let, our console produces two different lines,
5 and 10. This is because let is assigned to its current scope – so setting
myVariable to 10 in a separate scope does not affect the original
variable. If we used var instead, both lines would say 10 since scope
is ignored
var myVariable = 5
22
Chapter 2 Code Structure and Logical Statements
The reason why we use let rather than var is because var has a few
quirks that let does not. For example, you can define a variable twice with
var, and no errors will be thrown:
var myVariable = 5
var myVariable = 10
console.log(myVariable)
Variables defined with var are also not block-scoped, meaning your
code can produce some odd results when redefining variables in block
scopes with var.
You may be wondering, “Why does JavaScript have two ways of
defining variables when let is a more controlled version of var?” The
answer to that is pretty simple, and it’s because var used to be the only
way to define variables in JavaScript, and a lot of legacy code uses it. Later
on, JavaScript created a better way to define variables using let, but var
couldn’t be removed since it would break many older code bases.
let myVariable = 5
myVariable = 10
console.log(myVariable)
23
Chapter 2 Code Structure and Logical Statements
While this works for let, it will not work for const. Variables defined
with const are constants and cannot be reassigned:
const myConst = 5
console.log(myConst)
If you try to reassign the value of a const variable, you’ll get an error instead.
const myConst = 5
myConst = 10
console.log(myConst)
Using const to define variables is better when you’re able to use it. To
understand why, you can think about the example we discussed earlier where
we used let to reassign a variable from “5” to “10”. We talked about how the
value “5” still exists in memory unless it gets garbage collected. Since const
variables cannot be changed, garbage collection never has to run. That means
less cleanup is required, resulting in more efficient memory utilisation.
24
Chapter 2 Code Structure and Logical Statements
Arrays can contain a lot of data, and we can push new data to an array
using a special method called push:
By using push we can mutate our array, meaning the underlying data
changes and the data continues to be referenced and stored in the same
place. In other words, we did not create new data and point our variable
somewhere else, but instead mutated the original data.
This is confusing to beginners since the array was pointed to by a const
variable, so it would therefore be assumed that since the const variable is a
constant, the data inside must always remain constant. This is not the case
in JavaScript. So, in summary, while reassignment must remain constant in
a const variable, data mutation is fine.
let myVariable
console.log(myVariable)
This is sometimes done when a variable does not have a value when
you declare it but may be assigned a value later on in the code. When many
variables need to be declared without values, they can be separated by
commas. In the following example, we define three variables with the let
keyword:
25
Chapter 2 Code Structure and Logical Statements
Assignment Operators
Now that we’ve covered the basics of setting variables, let’s look at
assignment operators. These allow us to modify an existing variable, by
changing its value. For example, consider this variable:
let x = 5
let x = 5
x *= 5
console.log(x) // Console logs 25 (5 multiplied by 5 = 25)
There are many other assignment operators. They are shown in the
following example:
let x = 5
x *= 5
console.log(x) // Console logs 25 (5 multiplied by 5 = 25)
x += 5
console.log(x) // Console logs 30 (25 plus 5 = 30)
26
Chapter 2 Code Structure and Logical Statements
x /= 5
console.log(x) // Console logs 6 (30 divided by 5 = 6)
x -= 1
console.log(x) // Console logs 5 (6 minus 1 = 5)
x %= 4
console.log(x)
/*
Console logs 1 (if you divide 5 by 4, the remainder is 1.
% is the remainder operator
*/
Variable Concatenation
When we have variables that consist of at least one string, using the +
operator causes the strings to become concatenated. To understand this,
take a look at the following example, where we concatenate two strings
into a new variable:
// "hello world"
let combine = myVariable + " " + myOtherVariable
27
Chapter 2 Code Structure and Logical Statements
Just be careful, since if you try to use a + with numbers, it will add them
up instead!
let myVariable = 5
let myOtherVariable = 5
Different types of data have different built-in methods, which we’ll look
at in much more detail in future chapters.
Template Literals
Another final way to concatenate more elegantly is through a type
of functionality called template literals. Template literals are still strings, but
they use the backtick "`" to transform any content into a template literal.
Template literals have the added benefit of allowing line breaks – something
28
Chapter 2 Code Structure and Logical Statements
that numbers and quotation marks do not. They also allow for substitution.
Here is an example of a particularly messy template literal with line breaks
throughout:
Template literals like the preceding one will be taken with line breaks
and white space included – which means you’ll avoid loss of this content
when using them. They also allow for substitution. Adding a variable in ${}
will substitute it into a template literal:
JavaScript Comments
You may have already noticed that in the preceding code, I used double
slashes to leave some comments on what the code does. As our code
gets more complicated, it’s useful to leave messages to yourself or other
developers about what is going on. For this purpose, comments are used.
A comment in JavaScript can take one of two forms. The first looks
like this:
// I am a comment!
And the second looks like this, where the comment is enclosed in
/* and */:
/* I am a comment! */
29
Chapter 2 Code Structure and Logical Statements
Both work the same, but the second allows for multiline comments.
Comments have no bearing on the functionality of your code and instead
can provide useful information on what’s going on. For example, we could
comment our previous code like so:
Logical Statements
Now that we’ve covered variables, you’ll probably be wondering how we
can use them. Logical statements are one of the ways we can start to put
our variables to good use.
Logical statements are used when we want to check if something is
true or false and then run a particular action based on that outcome. If a
logical statement is found to be true, everything within its “block scope”
is executed. Likewise, if a logical statement is false, then the block scope
will never run at all. In other words, logical statements allow us to build
conditionality into our programs.
If…else Statements
if...else are perhaps one of the most commonly used logical statements
around. All they do is check if a statement is true. If it is, they run some
code, else, they run some other code. In the following example, we check
if myVariable is set to 5. If it is, we show “The variable is 5!” in the console.
If it’s not, then we show alternative text.
30
Chapter 2 Code Structure and Logical Statements
You can view this code running in Figure 2-4, where I run it directly
from the console in my web browser. You could also try this out by
updating your index.js file from earlier:
if(myVariable === 5) {
console.log("The variable is 5!")
}
else {
console.log("The variable is not 5.")
}
31
Other documents randomly have
different content
SOBERBA
Ô
«¡Ô fin sorte cansache!
Y o quiñon que famenta me negache
N’a hirencia d’os praceres,
Dándome só o d’as ansias e as peleas,
Cal á aqués que ben queres,
Ora darasmo en gustos âs mancheas.»
D’o tesour’escondido
O brilo e fermosura
¿Á quen que fose de muller nacido,
Á que mortal criatura
N’a houbera contrubado e seducido?
Á
Á tan grandes pracers, tan grandes males.»
* * *
Convidando á meditare,
Soan de Conxo as campanas,
Beben os bois n’o teu rio
Y o sol alegra a escampada.
D’as tuas casas terreñas
Say fume y os galos cantan...
¡Quen en tan fresco retiro
Dirá que as dores fan lama!
Cost’arriba, cost’arriba,
Desandemo-l-o camiño,
Fuxamos d’este sosego
D’os pesares enemigo.
¡Que negro contraste forman,
D’a natureza o tranquilo
Reposo, co as ansias feras
Que abaten o inxel esprito!
II
III
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
ebooknice.com