0% found this document useful (0 votes)
21 views

58863

Uploaded by

subbahkassir95
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views

58863

Uploaded by

subbahkassir95
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 66

Download Full Version ebookmass - Visit ebookmass.

com

How JavaScript Works: Master the Basics of


JavaScript and Modern Web App Development 1st
Edition Jonathon Simpson

https://ebookmass.com/product/how-javascript-works-master-
the-basics-of-javascript-and-modern-web-app-development-1st-
edition-jonathon-simpson-2/

OR CLICK HERE

DOWLOAD NOW

Discover More Ebook - Explore Now at ebookmass.com


Instant digital products (PDF, ePub, MOBI) ready for you
Download now and discover formats that fit your needs...

How JavaScript Works: Master the Basics of JavaScript and


Modern Web App Development 1st Edition Jonathon Simpson

https://ebookmass.com/product/how-javascript-works-master-the-basics-
of-javascript-and-modern-web-app-development-1st-edition-jonathon-
simpson/
ebookmass.com

JavaScript for Web Developers: Understanding the Basics


1st Edition Mark Simon

https://ebookmass.com/product/javascript-for-web-developers-
understanding-the-basics-1st-edition-mark-simon/

ebookmass.com

Learning Web Design: A Beginner’s Guide to HTML, CSS,


JavaScript, and Web Graphics 5th Edition, (Ebook PDF)

https://ebookmass.com/product/learning-web-design-a-beginners-guide-
to-html-css-javascript-and-web-graphics-5th-edition-ebook-pdf/

ebookmass.com

The Mail Order Bride's Secret Linda Broday

https://ebookmass.com/product/the-mail-order-brides-secret-linda-
broday-7/

ebookmass.com
Thermoelectricity and Advanced Thermoelectric Materials
Ranjan Kumar

https://ebookmass.com/product/thermoelectricity-and-advanced-
thermoelectric-materials-ranjan-kumar/

ebookmass.com

The Palgrave Handbook of Islam in Africa 1st Edition


Fallou Ngom

https://ebookmass.com/product/the-palgrave-handbook-of-islam-in-
africa-1st-edition-fallou-ngom/

ebookmass.com

Ethical Problems in the Practice of Law (Aspen Casebook


Series) 4th Edition, (Ebook PDF)

https://ebookmass.com/product/ethical-problems-in-the-practice-of-law-
aspen-casebook-series-4th-edition-ebook-pdf/

ebookmass.com

Medicinal Plants in Asia and Pacific for Parasitic


Infections: Botany, Ethnopharmacology, Molecular Basis,
and Future Prospects Christophe Wiart
https://ebookmass.com/product/medicinal-plants-in-asia-and-pacific-
for-parasitic-infections-botany-ethnopharmacology-molecular-basis-and-
future-prospects-christophe-wiart/
ebookmass.com

The House on the Hill Irina Shapiro

https://ebookmass.com/product/the-house-on-the-hill-irina-shapiro/

ebookmass.com
Eastern Front 1945: Triumph of the Soviet Air Force 1st
Edition William E. Hiestand

https://ebookmass.com/product/eastern-front-1945-triumph-of-the-
soviet-air-force-1st-edition-william-e-hiestand/

ebookmass.com
Jonathon Simpson

How JavaScript Works


Master the Basics of JavaScript and Modern
Web App Development
Jonathon Simpson
Belfast, Antrim, UK

ISBN 978-1-4842-9737-7 e-ISBN 978-1-4842-9738-4


https://doi.org/10.1007/978-1-4842-9738-4

© Jonathon Simpson 2023

This work is subject to copyright. All rights are solely and exclusively
licensed by the Publisher, whether the whole or part of the material is
concerned, specifically the rights of translation, reprinting, reuse of
illustrations, recitation, broadcasting, reproduction on microfilms or in
any other physical way, and transmission or information storage and
retrieval, electronic adaptation, computer software, or by similar or
dissimilar methodology now known or hereafter developed.

The use of general descriptive names, registered names, trademarks,


service marks, etc. in this publication does not imply, even in the
absence of a specific statement, that such names are exempt from the
relevant protective laws and regulations and therefore free for general
use.

The publisher, the authors, and the editors are safe to assume that the
advice and information in this book are believed to be true and accurate
at the date of publication. Neither the publisher nor the authors or the
editors give a warranty, expressed or implied, with respect to the
material contained herein or for any errors or omissions that may have
been made. The publisher remains neutral with regard to jurisdictional
claims in published maps and institutional affiliations.

This Apress imprint is published by the registered company APress


Media, LLC, part of Springer Nature.
The registered company address is: 1 New York Plaza, New York, NY
10004, U.S.A.
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.
Table of Contents
Chapter 1:​Introduction to JavaScript
JavaScript Fundamentals
JavaScript’s Type Classification
What Is JavaScript Used For?​
Writing JavaScript
Summary
Chapter 2:​Code Structure and Logical Statements
Getting Started
Common Code Conventions
Semicolons
Spacing
Variable and Function Naming
JavaScript Variables
Setting Variables with let
Setting Variables with var
Setting Variables with const
Defining Variables Without Values
Assignment Operators
Variable Concatenation
JavaScript Comments
Logical Statements
If…else Statements
Switch Statements
Block Scoping with Logical Statements
Conditional Operator in Variables
Logical Statement Comparison Operators
Logical Statement Logical Operators
Summary
Chapter 3:​Introduction to Objects, Arrays
Arrays
Getting the Length of an Array
Getting the Last Element of an Array
Array Manipulation Methods
Push and Unshift
Pop and Shift
Splice
Objects
Accessing Object Data
Object Mutability
Spread Syntax or the “Three Dots”
Prototype-Based Programming
Prototypical Inheritance
[[Prototype]] vs.​prototype (and _​_​proto_​_​)
Object Shallow and Deep Copies
Summary
Chapter 4:​Loops and Iterables
Loops
Break and Continue in Loops
Loop Labels
Iteration
Iterables and For Loops
Array forEach methods
String Iteration
Iteration Protocol
Objects Are Not Iterable by Default
Summary
Chapter 5:​References, Values, and Memory Management
Introduction
Stacks
The Event Loop
The Heap
Object and Reference Equality
Summary
Chapter 6:​Functions and Classes
Introduction to Functions
Running Arguments with the “Three Dots”
Alternative Ways to Call Functions
Unnamed Function Expressions
Anonymous Functions
Functions with Arrow Notation
Functions and the “this” Keyword
Sloppy Mode
Arrow Notation Functionality with this
Calling Functions with Context
Constructor Functions in JavaScript
Additional Function Methods
Getters and Setters
Generator Functions
Classes
Classes and Constructor Functions
Class Methods
Class Method Types
Class Inheritance via Extends
Summary
Chapter 7:​Types
Primitive Types
Primitive Wrappers
Using Wrappers to Create Types
The Number Type and NaN
Number Type Mathematics
Mathematical Methods
The Date Type
The Symbol Type
Truthy and Falsy Types
Truthy and Falsy Operators
Logical AND Operator
Logical OR Operator
Nullish Coalescing
Optionality
Summary
Chapter 8:​Manipulating and Interacting with HTML
Window and Document Objects
The Window Object
The Document Object Model
Selecting HTML Elements
The Order of HTML
NodeLists and HTMLCollections
Manipulating HTML After Selection
Adding Events to HTML Elements
Creating a Modal Window
Creating a Counter
Event Types
Drag and Drop
The e variable
Creating New Elements with JavaScript
Manipulating CSS with JavaScript
HTMLElements and Changing Styles in JavaScript
Adding New Style Sheets to HTML Pages
Setting CSS Variables
Getting CSS Properties and HTML Dimensions
Summary
Chapter 9:​Maps and Sets
Sets
Modifying Sets
Checking Set Membership
Checking Set Size
Merging Sets
Set Iteration and Values
Maps
Retrieving Map Properties
Checking for Key Existence on a Map
Telling How Big a Javascript Map Is
Iterating, Merging, and Accessing Maps
Keys and Values in Maps
Serialization of Maps in JavaScript
Summary
Chapter 10:​Fetching Data, APIs, and Promises
What Are APIs?​
Understanding HTTP
RESTful Design
Understanding APIs Through a Node.​JS Web Server
Testing Endpoints with Postman
The Benefits of APIs
Sending Data to APIs with JSON
The fetch Function
A Deep Dive into Fetch Options
Asynchronicity and Promises
Promise Methods:​then, finally, and catch
The await Keyword
Useful Promise Methods
Summary
Chapter 11:​Introduction to Web APIs
Web APIs
Frequently Used Web APIs
URL API
Web Storage API
Web Notifications API
History API
Summary
Chapter 12:​Errors and the Console
The Console Object
Console Errors, Debugs, Warnings, and Info
Console Timing
Console Counting
Other Useful Console Methods
Console Grouping
Console Tables
Errors and Exceptions
try…catch
Generating Errors
Handling Specific Errors
Summary
Chapter 13:​The Canvas
Introduction
Drawing and Images
Drawing Rectangles
Drawing Circles
Drawing Triangles
Drawing Images
Drawing Text
Interactivity and Creating a Drawing Application
Animations
Summary
Chapter 14:​Web Workers and Multithreading
Introduction
Using Web Workers
Sending Messages to and from Web Workers
Restrictions on Web Workers
Conclusion
Index
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.
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.
© The Author(s), under exclusive license to APress Media, LLC, part of Springer Nature 2023
J. Simpson, How JavaScript Works
https://doi.org/10.1007/978-1-4842-9738-4_1

1. Introduction to JavaScript
Jonathon Simpson1
(1) Belfast, Antrim, UK

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:
Client-side code, which we’ll refer to as “the front end,” which is
included via HTML files and adds interactivity to websites. Client-
side code is loaded and processed directly on someone’s web
browser or device. In practice, this means writing a .js file or HTML
file containing JavaScript and loading it directly into your
web browser.
Server-side code, which we’ll refer to as “the back end,” which is
used for writing web servers. This kind of code is written on web
servers and can be used to create things like APIs which the end user
never directly sees. It uses a runtime to execute the code on web
servers. The most common runtime used for this is called Node.js.
Server side code is loaded and processed on a server that is separate
from the user’s device.
Everything we discuss in this book will be applicable to both front
end and back end, but our focus will be on front-end JavaScript since
that’s where JavaScript started. We’ll sometimes touch on back-end
JavaScript where necessary so that certain concepts can be more easily
understood.

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.

JavaScript’s Type Classification


How a language is typed usually gives us a broad idea of how it works.
Like most other languages, JavaScript lets you define “variables” to
store data, and these variables have types. “Type” refers to the kind of
data being used. For example, a number is of type Number, and a
mixture of characters and/or numbers is referred to as having a type
called String.
If you have used other languages, JavaScript may seem different
since it is weakly typed. That means that while other languages
require you to explicitly mention in the code what type of data different
variables are, JavaScript does not. JavaScript is also often referred to as
dynamically typed, meaning it will dynamically interpret what type of
data is based on the context it finds it in.
To understand this better, let’s look at how variables are defined in
JavaScript. Usually, we define them like this:

let x = "Some String"


let y = 5
let z = false

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.
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.

What Is JavaScript Used For?


As we mentioned in the introduction, JavaScript can be compiled and
used in two major ways. The first is to create front-end interactive
experiences, right in your browser. The second is as back-end server
code. Front-end JavaScript is rendered by the browser inside of web
pages, while back-end server code requires a runtime like Node.js,
which compiles the code you write to run it directly on the server.
When inside the browser, some of the major things JavaScript can
do are
Adding, changing, or deleting CSS/HTML when a user interacts with
something.
Creating new HTML tags programmatically.
Tracking user action and producing feedback to the user (such as
showing a pop-up when a user clicks on something).
Storing data for the user locally via local storage or cookies.
Creating single-page user experiences where no page refreshing is
needed.
On the back end, the main use cases are
Creating routes/URL endpoints on a server and dictate what happens
if a user navigates there.
Creating routes/URL endpoints for APIs (application programming
interfaces), so we can send and receive data to and from the server.
Building WebSocket servers, which users can interact with from their
front-end experience. These can be used for making things like chat
rooms.
Compressing pre-rendered web pages for a faster web experience.
Manipulating data sent to the server (sometimes via WebSocket or
API) and store it in a back-end database.

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>
<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.

In the preceding example, we inserted a <script> tag within our


HTML body. The <script> tag is where our JavaScript goes:

<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>
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:

<button onclick="//JavaScript here"></button>

Setting Up a Code Editor


Throughout this book, I will be writing code using Visual Studio Code or
VS Code. If you do not have a preferred code editor, I would strongly
recommend using VS Code, which you can download via the official
website (https://code.visualstudio.com).
Although it is possible to build a software career through Notepad,
it’s not recommended. Modern code editors like VS Code give you a ton
of useful features, including code highlighting which makes it easier to
read what you’re writing. They also come with more advanced features
like built-in terminals, for when you need those things.
If you download VS Code, you’ll be greeted with a screen that looks
like the one shown in Figure 1-1. From there, you’ll be able to make
new files and folders for storing your projects in.
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

Starting Up Our Code


The fun thing about writing front-end JavaScript is that once you save
your .html file, you can load it directly in any web browser to test it
out.
Try it out by opening index.html in your web browser, either by
dragging it into the window or by opening it via File ➤ Open File….
To see your code in the browser itself, you can right-click on the
web page anywhere and choose “Inspect” in Google Chrome. If Chrome
is not your browser of choice, similar functions exist in other browsers
too. Using “Inspect” will also let you see supplementary information
about what you’ve created, as Figure 1-2 shows.
Figure 1-2 “Inspect” or “Inspect Element” lets you view more information about your code in
the web browser

“Inspect” or “Inspect Element” is a vital tool in web development.


Throughout this book, we’ll use the console tab within developer tools
to test out code and see the results of code we run. As such, it’s very
useful to familiarize yourself with this display now.

How to Get Started with Writing Back-End JavaScript


We’ve now discussed how JavaScript can be run inside a web
browser like Google Chrome. Before we go any further, let’s briefly look
at how we run back-end JavaScript too, which we’ll occasionally touch
on in this book. Back end JavaScript runs directly on your computer or a
web server instead of inside a web browser. To run JavaScript like this,
you need to use a runtime like Node.js.
Node.js can be downloaded and installed on your computer via the
official Node.js website (https://nodejs.org/en/download).
After it has been installed, you’ll be able to run JavaScript code directly
from a terminal window by executing your .js file.
You can do that by opening the terminal or command line on your
computer, which is accessible on MacOS via the terminal app or on
Windows via the “cmd” application.
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.

Figure 1-3 Running a JavaScript script from the command line is as simple as using the “node”
command followed by the directory link to the file you want to run

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.
Node.js applications like this are frequently used to create APIs,
which we will cover in much more detail later in the book.
Creating Node.js JavaScript Projects
In the above example, we executed a single file using Node.js It is more
common, though, to create a Node.js project when you start something
new in Node.js. This is also done via terminal or the cmd. The first step
is to make a new folder and navigate to it using the cd command.
In this example, I made a folder called “node-project” on my desktop
and navigated to it using the following command in Terminal:

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.

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 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.
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.
© The Author(s), under exclusive license to APress Media, LLC, part of Springer Nature 2023
J. Simpson, How JavaScript Works
https://doi.org/10.1007/978-1-4842-9738-4_2

2. Code Structure and Logical


Statements
Jonathon Simpson1
(1) Belfast, Antrim, UK

In the previous chapter, we covered the fundamental definitions of


JavaScript and where we write it. Now that we’ve discussed the basics,
let’s start learning about how we write JavaScript code. In this
chapter, we’ll cover the fundamentals, which includes code structure,
logical statements, and variables. Mastering these concepts is a
requirement to writing useful JavaScript code. Where relevant, we’ll
also be diving deeper into how these basic concepts actually work, so
that you have a deeper understanding of the code you are writing.

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!")

The console.log method is really useful. It’s used extensively for


debugging, and we’ll be using it throughout this book. When it’s run, it
logs a message to your browser’s console, so that you can see the
output of your code easily. You can find the console by right-clicking
anywhere on your web page and selecting “Inspect.” Console logs can
then be viewed under the “Console” tab, as shown in Figure 2-1.

Figure 2-1 Right-clicking in the web browser and selecting “Inspect” in Google Chrome (or
other browsers) allows you to access the console log. If you do this with the index.html file we
defined before, you’ll see “Hello World!” written here. The console is a powerful tool used for
debugging. When we use the console.log method, it shows up here!

Common Code Conventions


Before we start writing real code, let’s first consider some basic code
conventions. As is the case in most programming, developers of
JavaScript try to follow some common conventions when writing code.
This section is largely opinionated, but it does provide you with
guidelines on how you should go about writing JavaScript. It will also
let you know how we will go about writing code throughout the book.

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!")

We can do this because JavaScript will intuitively “figure out” where


semicolons should go. It even works if you do an accidental line break
where an expression seems incomplete. For example, if a line ends with
a + symbol, JavaScript will assume that the expression must continue
onto the next line, meaning the code will still work as expected:

console.log(5 +
6)

For the code in this book, we will be omitting the semicolon unless
it is really needed.

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.

Variable and Function Naming


When it comes to naming functions and variables, you’ll come across
three different paradigms: camel case, pascal case, and underscores:
Camel case refers to naming a variable where every word after the
first has a capital letter, for example, thisIsCamelCase.
Pascal case is the same, except the first letter is capitalized too. For
example, ThisIsPasalCase.
Underscoring refers to separating words with underscores. For
example, these_are_underscored.
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
All JavaScript variables are case-sensitive, so myVariable is
different from MYVARIABLE. In JavaScript nomenclature, we
usually say that we “declare” variables.

Setting Variables with let


Most variables in JavaScript are set with let. A variable set with let
starts with the keyword let, followed by the variable name and an
equals sign, and then the value of your variable. In the following
example, we create a variable called myVariable, and console log it so
that it appears in the browser’s console:

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)

Figure 2-2 Variables defined with let cannot be defined multiple times. If you try to, it will
produce an error like the preceding one

So variables defined with let cannot be redefined again. They can,


however, be reassigned to a new piece of data by mentioning them
again without the let keyword. You can see that in the following
example, which console logs “10,” since we changed the value of
myVariable:

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.

Block Scoping with Variables


In the previous example we saw that it is not possible to define the
same variable, but there are exceptions to this. That’s because variables
defined with let are block-scoped. Scope confines functionality,
variable names, and values to certain sections of our code.
Block scopes are created with curly brackets {}. In most scenarios,
we create block scopes by defining new functions or logical statements.
Since standalone curly brackets also create a new block scope, a
variable can be set twice simply by defining it again inside { } curly
brackets:

let myVariable = 5

{
let myVariable = 10
console.log(myVariable)
}

console.log(myVariable)

Even though we created the same variable twice, no error is thrown,


and that’s because one is assigned to a new block scope. The first
variable is assigned to the “global” scope of our program, while the
second is assigned only to the “curly bracket” scope. The outcome of
this can be seen in Figure 2-3.

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
Setting Variables with var
Most variables are set with let, but you may also see the keyword var
being used to set variables sometimes. Using var is the original way to
set variables in JavaScript. It is valuable to know this exists, but it is
generally not recommended that you use it over let.
Setting a variable with var looks a lot like what we did with let.
For example, here is a variable called myVariable, with a value of 5:

var myVariable = 5

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.

Setting Variables with const


The final variable type we will cover is const. When we defined
variables with let, we talked about how a variable can be reassigned
to another value:

let myVariable = 5
myVariable = 10
console.log(myVariable)

Remember, we don’t actually change or “mutate” the data here – we


just create new data and “re-point” our variable to that new data
source.
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.

Mutation of const Variables


Variables cannot be reassigned with const, but they can be mutated.
That’s because reassignment and mutation are not the same thing.
When we reassign a variable, no data changes – but it is possible to
change underlying data in JavaScript using mutation instead. In
JavaScript, mutation of primitive values like numbers, strings, and
booleans is not possible, but objects can be mutated.
We will cover how arrays and objects work in more depth in the
next chapter. For now, all you need to understand is that arrays and
objects are containers of data. An array can be defined as shown in the
following example:
const myArray = [ "some", "set", "of", "content" ]
console.log(myArray)

Arrays can contain a lot of data, and we can push new data to an
array using a special method called push:

const myArray = [ "some", "set", "of", "content" ]


myArray.push("new data!")
console.log(myArray)

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.

Defining Variables Without Values


It is also possible to define variables that point to nowhere. If you try to
console log a variable with no value assigned, you will get undefined
as a result:

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:

let myVariable, myOtherVariable, myFinalVariable


Although comma notation like this is more commonly used with
variables that have no value, you can declare variables with values this
way too:

let myVariable = 5, myOtherVariable = 4,


myFinalVariable = 3

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

Suppose we wanted to multiply x by 5. One way is to reassign x to 5


* 5, but a better way is to use an assignment operation. The reason it’s
better is because x may not always be 5, so this is particularly useful if
we want to change the value of variables based on conditions (which
we will cover in more detail in the following).
To multiply x by 5, we use the *= assignment operator:

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)
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:

let myVariable = "hello"


let myOtherVariable = "world"
let combine = myVariable + myOtherVariable //
"helloworld"

If we need a space too – we can add that with another +:

let myVariable = "hello"


let myOtherVariable = "world"

// "hello world"
let combine = myVariable + " " + myOtherVariable

Just be careful, since if you try to use a + with numbers, it will add
them up instead!

let myVariable = 5
let myOtherVariable = 5

let combine = myVariable + myOtherVariable // 10

This brings us to a new quirk caused by JavaScript’s dynamic typing.


If a number is in quotation marks, it is assumed to be a string. Adding a
number and string results in a new concatenated string instead of a
calculation:

let myVariable = "5"


let myOtherVariable = 5

let combine = myVariable + myOtherVariable // "55"

Another way to combine string variables is with a special method


called concat. This is a method that exists on all strings, which will
add to the end of a string any number of new things that we separate
with commas:

let myVariable = "hello"


myVariable.concat(" ", "world", "!") // hello
world!

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 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:

let myVariable = `hello world


!!
how are you?`
Random documents with unrelated
content Scribd suggests to you:
They shook hands gravely. Cecily went away with a sense of outrage and
justification. So that was Fliss!

There was a small dinner at the Garden House Club, for Mrs. Walter
Warner, the next week. Della was taking rather well on the whole. Mrs.
Longstreet, who liked to “bring out” young people, was the hostess. The
Walter Warners, the Richard Harrisons, the Matthew Allenbys, the
Frederick Craigs, Madeline Ensign and her husband, Gordon Ames, the boy
who had so vainly pursued Fliss and who, with college back of him and a
start in his profession, was no longer a boy but a much sought after man,
Helen Jefferson, because every one hoped that Gordon would marry her,
and a half-dozen other couples—all young, all extremely well acquainted
with each other. Della was quite at her best. With nothing to do except be
nominal mistress of her mother-in-law’s home and plenty of service at her
disposal, Della was keeping in excellent form. It was easy to see to-night
why Walter had fallen so very much in love with her. Her pale yellow hair
was like a mist around her head and the green of her gown was either a
stroke of luck or a stroke of genius, thought Cecily. She looked curiously at
Fliss in the light of the revelations of her call on her mother the day before.
Fliss evidently did not know about that yet or if she did she made no
reference. She greeted Cecily casually and turned back to the glass.
“Just below your cheek-bones, my dear. Most people put it on too high
up. It gives much more the look of youth, not that you need that, but you
know.”
Della experimented. Cecily looked over their heads at her own hair,
combed heavily back in dark waves, at her own cheeks faintly pink with
cold. She had it in mind to disdain rouge, but Fliss’s professionalism was
tantalizing. She opened her little gold case and gave her cheeks a touch of
red below the cheek bone.
“You don’t need it, Cecily. You’re better without,” said Fliss, observing.
“Cecily’s always better looking than anybody else,” contributed
Madeline. “You really are, Cecily.”
Della gave Cecily a critical glance. “It’s much easier for a brunette,” she
sighed.
That brought her the anticipated compliments from the rest. Cecily did
not join them. She was watching Fliss and Della, suddenly mindful that it
had not been so long ago when Fliss was more or less outside of all this
easy fun. She looked back over the obvious steps of the progress Fliss had
made. Funny! And that queer-looking woman in the soiled kimono dying of
cancer; and out there Matthew waiting for his wife to take her to their
hostess, to pay her honor. She wasn’t worth it. Walter waiting for his wife,
for the girl who had pulled him out of college into marriage, who had
probably tricked him, who had no respect for marriage. She wasn’t worth it,
either! Worth what? She caught her mind back and began to talk to
Madeline as they strolled out into the little reception room to meet their
husbands.
At dinner she sat between Freddy Craig and Howard Ensign—rather on
the dull side of the table. Fliss above and across from her had Dick and
Gordon Ames, and Della on the right of her host was dividing her attentions
between him and Matthew. Cecily talked at random, intermittent, necessary
conversation, her mind and eyes straying to the brightness of Fliss. She
seemed so eager and Dick seemed so pleased by her eagerness and so alert.
She couldn’t make it out. No right—no wrong. Why can’t I be like the rest
of them, she thought, immediately conscious that to be like the rest of them
was just what she did not want.
Fliss was telling Dick something sotto voce. He listened closely and then
broke into irrepressible laughter. Fliss looked at him provocatively and his
eyes were slanting down at her in that amused, liking way.
Howard Ensign was following Cecily’s eyes.
“Isn’t Mrs. Allenby a lot of fun?” he asked.
“Oh, yes,” answered Cecily, mechanically, “lots of fun.”
“She gives everybody such a good time.”
Fun. That was it. Fun, that god whom they all worshiped. Like a heathen
god, like a great bright image, casting great shadows. Queer thought. She
sat in the shadow while they worshiped the brightness. An impulse came to
Cecily to call to Fliss to stop. She was pinning a flower in Dick’s
buttonhole. It was a wager or a joke. Everybody was laughing. She had no
right to touch Dick like that. Dick didn’t care. Dick had no pride, no self-
respect, no respect for love,—or he wouldn’t let her touch him like that. She
was caressing him.
Fliss caught her glance. “Mustn’t, Dick,” she said, laughingly. “Your
wife’s looking at me. She has her till-death-do-us-part look on.”
Her voice carried and they turned to look at Cecily—all the people at the
end of the table—merrily, jocularly. Cecily tried to smile, tortured by the
glances that seemed to be penetrating her thoughts. Dick looked a little
annoyed.
“Don’t be worried, Cecily.” Fliss wouldn’t leave her alone.
“I wasn’t worried.” Now they were laughing. That wasn’t what she
should have said. She should have been light, gay, debonair, flippant. Why?
Because that was what they expected.
Like a match to a gathered pile of brush were the comments to Cecily’s
resentment. She was suddenly angry as she had never been angry before in
her life—cruelly angry. She wanted to hurt them all—Fliss, Della most. But
her opportunity did not come till later.
Howard found her better company. She talked to him now, seeming to
insist on talking. He told her about how he thought game should be cooked,
about the new club rules for membership, about the things he was interested
in. She answered him, played up to him, her mind alert, her eyes casually
now on that other end of the table.
“We’ll get up a party and go,” she heard Dick say. They were drinking
coffee. Fliss was devoting herself more to Gordon. There was a smoldering
look in Gordon’s eyes that Cecily read and that it shamed her to read. He
looked as if the presence of people, of Matthew himself, hardly interested
him. He wanted to slip his arm down close around her, bend his head lower.
Dick was competing for her favor, actually competing.
“We’ll get up a party,” he repeated. “There’s a tiled floor and the funniest
nigger band you ever heard. You’ll love it, Fliss.”
“All right,” said Fliss. “Will you come along, Cecily?”
That was to demonstrate her power, thought Cecily. Fliss was asking her
to a party with her own husband.
“If I can,” she answered coldly. “If I get a cook and can manage to get
out.”
A little smile of pitying superiority to one so tied down by domestic
affairs showed on Fliss’s face.
“Miserable luck, Cecily.” Then to Dick, “Do you starve without a cook,
poor Dick?”
Like a flash Cecily struck back. Cool and icy and penetrating her voice
carried down the table length.
“I think I’ll have my old cook back shortly. She is nursing your mother
now, you know, Fliss.” And to her neighbor quite clearly, “She had to go to
Mrs. Horton, of course, because she is her cousin.”
There was the faintest little smile, the smallest hush. Mrs. Longstreet’s
eyebrows went up and then down,—her only signal of lack of equilibrium.
Then she rose and the company followed. Only in that instant Cecily had
seen Dick’s angry glance and the cruel flush that had risen on the face of
Fliss. It delighted her to see that the blow had gone home. Then an acute
sense of degradation swallowed up her delight.
Dick did not claim her for the first dance. It was Fliss he danced with.
When he did come to his wife, he looked at her with his eyes still angry.
“Dance this, Cecily?”
“Where did you learn that raw stuff?” he asked after they had been
around the floor silently.
“What do you mean?”
“You know what I mean. That was a pretty raw attack on Fliss.”
“Attack?”
“Attack was what I said.”
“You mean when I mentioned to Fliss that her cousin couldn’t come to
cook. I hadn’t told you, had I, that Ellen was a cousin of the Hortons’.”
“I can’t see that it is of much consequence whether she is or not, but you
knew how a lot of those people at dinner would make capital of it. It was a
deliberate attempt to hurt her. I can’t see why you should do such a thing.”
“You ought to know why,” said Cecily. “You ought to know why.
Because that woman is dangerous. Because she’s unworthy. She was flirting
with you and with Gordon Ames—she was acting like a bad woman—
leaning on you.”
“Don’t be so cheaply jealous.”
“I’m going home,” declared Cecily. “I won’t stay here in this place.”
“Very well. You’ve ruined a delightful party anyhow. Will you say good-
night?”
He did not speak to her on the way home, unlocked the door for her and
then when she was in the little vestibule said coolly, “I’m going to the club
for a couple of hours. Good-night, Cecily.”
The door closed and Cecily went upstairs, her throat choking her. Anger,
resentment, but most of all the terrible agony of thought that they had
quarreled again and that Dick could not see what she saw nor feel what she
felt! Softly she stole through the nurseries so that the children might not be
wakened. The sight of them gave her no joy to-night. Only deeper pain and
deeper sense of failure! Yet it was some comfort to touch the baby hand
lying on Dorothea’s little coverlet, so warm, so confiding even in her sleep.
She thought as she stood there of the people who say that they could absorb
themselves in their children. Surely even children did not fill up all the
spaces in life; not for her anyway could they suffice.
At first she thought Dick would be gone only an hour. She undressed
slowly, planning what she would say to him. It became clearer to her that
she had been shabby and unworthy. She would tell Dick she was sorry,
make it up somehow. The hour passed. She crept into bed and waited. But
he did not come. One o’clock—half past one; Cecily got up, tormented by
the waiting and all the possibilities it suggested. Where was Dick? Wasn’t
he coming back at all? Was it possible that he had left the city? Had there
been an accident?
The children slept on. The house was terribly still. She tried to read, tried
to think, wrote a note to Dick and placed it on his bureau, only to go in and
destroy it after another half hour’s waiting. She thought she would go mad
with anxiety. She determined to be quite indifferent. She would not care if
he did not. Again she slipped into her bed and this time fell asleep.
When she awoke it was daylight and the telephone was ringing in the
distance. She heard the maid answer, heard Dick take the call on his
extension. He was home then. He must have come in after half past two.
The murmur of his voice was indistinct. She lay there feeling as if she had
been beaten; physically tired from the strain of the night before. The
children were being dressed in the nursery. She wondered what the
inefficient woman in the kitchen was doing, but the routine did not stir her
to action as it usually did.
She heard Dick still telephoning. A sick feeling at the thought of meeting
him came over her. Would he come in or would he appear at breakfast,—
cold, condemning, unjust?
He came in. She braced herself a little, but there was no need. He came
swiftly over to her and stood looking down at her, his face troubled, pale.
She had not guessed that he would feel like that.
“Cecily, I’ve got to tell you something dreadful. Are you going to be
game—brave, darling?”
He was in love with Fliss; he was going to go away from her. She sat up,
her hand against her throat to keep back the scream which she felt might
come.
Dick sat down beside her and went straight through it.
“Last night Walter found me at the Club. He had a garbled telegram and
we spent hours trying to get at the facts. When I came in you were asleep
and I wanted you to get the sleep so that you could bear this better.”
“This—this?”
“Darling, your father wired that your mother died of pneumonia at seven
o’clock last night.”

CHAPTER XX

M RS. WALTER WARNER, in the most elaborate of mourning clothes,


ordered from New York, still held sway in her mother-in-law’s house.
It seemed probable that she always would be there now. Since his
wife’s death, Mr. Warner had come to “depend” on Walter, and if depending
on Walter meant inoculating himself to the elaborate black and white
(mostly white) of Walter’s wife’s costumes and enduring Della at his table,
apparently he was able to put up with that too. Della was nice to him. She
said to her friends that she meant to be “nice to poor old Mr. Warner,” and
proceeded to take charge of his house, enlarge his bills and with the
immense insolence that was hers also began to take to herself considerable
credit for doing so.
It was two months since her mother’s death and for the first time Cecily
felt able to begin the task of looking over her mother’s personal
possessions. Mr. Warner had given few directions, expressed few wishes,
but on that point he had been explicit.
He had closed and locked his wife’s room and said to Cecily, in giving
her the key to the room and to the little safe in it—“I have taken the few
things from it that I wish to have remind me of her. I have not opened the
safe. The things there and the other things are yours and Dorothea’s. And,
of course, Cecily, you are no less my daughter. You and the boys are to
share equally in my estate, which was also your mother’s.”
“Not now—please,” answered Cecily. “I’ll go over the things when I
can.”
As Della said to Walter, it wasn’t as if Cecily could possibly wear all that
jewelry herself. It seemed a kind of waste. Walter gave her one of the looks
which he had learned how to give her when he was disgusted, and she
tossed her head and reserved her comments for her more intimate woman
friends.
So on this bright May morning Cecily sat in her mother’s room on the
little hassock by her mother’s chaise longue and looked about her at the
objects that had become freighted with memory, wondering just what her
mother’s inward life had been, where it had hurt her most, what she had
loved most.
The lovely gowns in their chintz wrappers each brought a pang of pain.
She could see her mother in them—lovely, gracious, charming, every one—
and now they could no longer be given life. They were empty, meaningless
decorations. The softest satins—the dresses which “looked like her
mother”—she laid away in a deep mahogany chest. They were to be for
Dorothea some day to carry her the spirit of a past. The dressing table
fittings she would take, too, and the little objects around the room that her
mother had loved to look at. She would hang that head of the Madonna,
which her mother had found in Italy, at the foot of her own bed. It was a
long, sad task for Cecily, but with flashes of comfort. She had the sense of
being close to her mother again.
At last she opened the little wall safe which her mother had had
constructed. The red jewel case of velvet was there with all but the few
jewels which Mrs. Warner had worn in California and which already had
been given to Cecily, to Della’s disgust. There was her mother’s pearl
necklace which Mr. Warner had given her; the diamonds which had been
the gifts of birthdays and anniversaries; the odd, exquisite things which
Mrs. Warner had brought for beauty’s sake; other jewels, too, which Cecily
had never seen; that other wedding ring, engraved with name and date. It
gave her a stir at her heart. That wedding ring had meant her—Cecily.
A cabinet photograph of her father—handsome, queerly out of fashion.
She pondered the photograph. There was a look of her little Leslie, named
after Mr. Warner. Strange to have Mr. Warner’s name carried on through
this child who looked so much like Allgate Moore.
Envelopes with baby pictures of herself, that brought the tears to her
eyes. Letters. Letters which must have been written from her father to her
mother. Yes. She had kept those, then. She had wanted to preserve, even
through the pain, these letters which must have been letters of love from her
father. Even through the disappointment and the infidelities. It did not occur
to Cecily to read them. She took them to her mother’s little fireplace and
burned them there. They had no meaning now to any one alive.
There were other pictures; a funny antiquated kodak picture of herself
held by her father and with her mother smiling at them. They looked so
happy! It hadn’t been all tragedy. She picked up a ring which she knew her
father had given her mother. She could remember that her mother had worn
it when she was a child and that she had loved to twist it on her mother’s
finger. It was a deep sapphire in a low odd setting of dull gold. Cecily
slipped it on her own finger.
“In memory of the happiness you gave my mother,” she said to the
handsome, smiling picture of Allgate Moore.
There was a knock on the closed door and Della entered forthwith.
“Nearly time for lunch, Cecily. How are you coming on? Is there
anything I can do to help you?” She spoke as if Cecily were packing a
trunk.
“No, thank you, Della.”
“Can I see?”
There was no proper reason for refusal, but it was hard to let her see.
Hastily selecting those souvenirs of the first marriage of her mother, Cecily
pushed the collection of other jewelry over to Della. Della gasped.
“What a lot! Are those real pearls? And you get everything! Of course
you’re awfully sad, Cecily, but you certainly are a lucky girl to get all these
lovely things.”
Cecily did not answer.
“It’s funny your mother didn’t make a will. She was awfully nice to me
always. I guess she was glad to have me take Walter in hand and get him
out of any wild ways. Mrs. Allenby was saying the other day——”
“Was saying something about my mother?”
“Oh, I forgot you don’t like her very well. I guess she’s hardly your type.
She’s so gay. But she’s awfully well liked and even if her family doesn’t
amount to much she always admits it. I was so surprised the night you told
everybody that her cousin was your cook. Ellen’s back with you, isn’t she?
Fliss isn’t hiding it, anyway. She tells it in such a funny way.”
Cecily could imagine that. She could guess how Fliss’s sharp tongue
could make ridicule of Cecily out of the fact that Cecily had tried to ridicule
her.
“Walter and I were at her house the other night——”
“Surely, Della, you aren’t going out yet; you’re in mourning!”
“I can’t absolutely stop seeing every one, can I?” said Della petulantly.
“Of course you have to remember that I was cheated out of a lot of things;
and I was a bride and all and just beginning to be entertained for.”
“Doesn’t father——”
“He never says a word. No, I think he’s glad to see Walter and me
having a little fun. I just told Walter that I felt that his first duty was to me.”
She stopped and bridled. “Of course, it’s your own business, Cecily, but I
think you’re making a mistake.”
The lift of irony was in Cecily’s voice. “I am?”
“Well, a man likes a good time and I should think Dick would get
awfully tired sitting around so much. Fliss says that when she first knew
him——”
“I can’t see any point to this kind of talk,” said Cecily, rising. “Did you
say that lunch was ready?”
She looked a little dowdy—felt a little dowdy beside the blond
completeness of Della. A disgust of all fashionable dress for mourning had
made her rather deliberately choose clothes that were not only not in
fashion, but which were somewhat clumsy. And she had cried a great deal
and her eyes were heavy and sad. Beautiful as she was, she excited no envy
in Della, except in so far as she possessed those jewels. Della knew what to
envy.
Cecily’s house was becoming a refuge for her. She felt it that afternoon
as she went back to it. The two eldest children were out in the garden with
their nurse, where the lilacs were beginning to bloom and the early green of
spring was so exciting and alluring. It cheered even Cecily’s rather dark
mood. Spring and healthy children and a home with Dick; what was it she
lacked—why was it that she and Dick lacked anything? It ought to be right
—it ought to be perfect; and it wasn’t right and it wasn’t perfect. Was Dick
cheap, or she deficient in charm? Was the clamor of light living and noise
eternally to make their home discordant? She would make it right. With her
and the children, with a gayety that was not tawdry; yes, for Dick she would
lighten her period of mourning. She looked back on her one talk with her
mother about herself and Dick and felt that her mother would want her to
make a concession to him. He had been so wonderfully kind during those
first weeks. It was only lately that he had seemed restless again and surely it
must be possible to swing back again to the beauty of those first years
together.

She found no opening.


Dick had gone to Matthew’s house for dinner, so he telephoned. “We
didn’t get through in time at the office,” he explained, “and I thought I’d
drop off here and finish what I wanted to take up with him. Children all
right?”
“Quite.” She hung up the receiver. It would have been just as easy to
come home, but he didn’t want to come especially. He wanted to go to
Matthew’s house. She sat through her dinner, which seemed perfectly
tasteless.
That night she waited up for Dick, conscious that it was not what he
would wish. He came in humming a little. She tried to look casual and
succeeded in looking tragic—so tragic that the blithe smile on his face
faded quickly into an annoyed concern.
“What’s up?”
“Nothing. I just thought I’d read a while.”
“You should be in bed. It’s nearly midnight.”
“I know.”
“Sure nothing’s wrong?”
“No.”
He turned to go up the staircase, but she caught him back with a little
cry.
“Dick, why aren’t we like we used to be?”
He looked at her almost with dislike. “Isn’t it late for psychological
discussion? What do you mean?”
She faced him with the question which was clamoring in her mind,
tugging at her heart all the time.
“Dick—do you love me?”
It jarred on him unspeakably—this forcing of emotion.
“Isn’t that rather an unnecessary question?”
“I’m afraid it isn’t.”
“I wish you wouldn’t be so high strung all the time, Cecily. I realize
you’ve had a bad time lately; in fact, it seems to me you’ve had a bad time
ever since we were married. But it does wear on me—this atmosphere of
tragedy.”
“Then why must we have it? It wasn’t like that when we were first
married.”
He took an impatient turn up and down the room.
“No. But you can’t maintain a honeymoon attitude all your life, my dear.
I don’t suppose we feel the same way towards each other as we did then.”
That hurt. “But why don’t we?”
“Why, we’re older; people’s emotions cool naturally.”
“But they shouldn’t if they love one another.”
“There you go, you see. You want to have everything your way. You
want to force things. You don’t let life be natural, Cecily. You’re too
romantic.”
The tears in her eyes only irritated him. He went on, thinking that it
might be as well to have it out with her.
“I don’t want to be unkind, but you have the most artificial view of
things sometimes. You can’t tolerate any thing or person that isn’t on a
pedestal.”
“No, it isn’t that, Dick. I just hate to see things slip into cheapness.”
“But almost everything normal to you is cheap.”
“No! All I want is to have you love me and the children—be content
with us.”
“You’re quite absurd, Cecily. I love the children as much as any man
could. If it’s hard to love you it’s because you scare me off by frowning
upon every harmless diversion—by wanting to shut us up together. That
isn’t the way people live nowadays. Marriage isn’t prison. The trouble with
us is that we aren’t congenial in our pursuits. You like one kind of thing. I
like another. And you won’t admit my kind of thing at all.”
“I don’t want marriage to be prison, but if marriage is anything surely
it’s the concentration of two people on making a home and bringing up their
children.” She couldn’t add love.
“It’s a lot more than that nowadays, Cecily. I suppose that used to be all
that was expected of a woman—having her children and keeping her house
clean. Now things have broadened. Men need more, ask more; so do most
women.”
“I suppose,” said Cecily, coldly, “what you mean is that men want a lot
of noise and dissipation and promiscuous flirtations, and that they expect
their wives to tolerate and join them in such things.”
The scorn in her voice drove Dick on. “Well, perhaps the woman who is
willing to do that gets away with marriage better than the woman who
clings to an outworn domesticity. I know your scorn of Della—and of girls
like Della and Fliss. We aren’t any happier than Fliss and Matthew, or Della
and Walter.”
Cecily became purely instinctive. She burst into tears and tried to talk
through them.
“Then the fact that I have three children and they have none doesn’t
make any difference to you?”
“The children are beside the point. I’m glad we have them; so are you.
But you can’t justify everything, excuse all unhappiness, swallow yourself
up, even in children. For God’s sake be reasonable, Cecily. Stick to the
point at issue.”
But she couldn’t. She lost her case, sadly undeveloped as it was, by her
rapidly mounting hysteria. It ended by her being put to bed, being soothed
by Dick, assured of things which he didn’t mean in his heart and which she
knew he didn’t mean—by the sleep of exhaustion and day of shamed
apology which followed for both of them.
CHAPTER XXI

I T could not last too long after that, but they ran the whole gamut of
possible moods. There were times when the antagonism between them
seemed to one or the other so intangible, so imaginary as to be ludicrous;
days when the air seemed cleared of dissension and unhappiness; any
incident could alter the whole shape of things for them. Some new delight
in the progress of the children, some anniversary which it seemed too cruel
to let pass in anger, would make them both happy. But they never quite
relaxed, never quite felt faith in each other. And the most trivial thing could
upset their balance—a fancied slight, a casual statement which was
translated into a criticism. On their guard constantly, neither of them felt
peace.
The days were absorbing for Dick just at this time, too. In July Matthew
had unexpectedly yielded to the pressure upon him to become a candidate
for United States Senator to fill the unexpired term of the incumbent who
had just died. He had refused many political honors and opportunities
before, but this time the political situation looked so black that he could not
justify refusal. He knew his usefulness well in a state where blind
conservatism and dangerous dissatisfaction were in constant ferment; and
his acquaintance and high standing among all kinds of men made his
nomination fairly certain. But his decision left Dick alone and depressed. It
was not that he did not approve of Matthew’s action, but that they had come
to depend upon each other more and more in business. They had worked
out the development of the mines together lately. With Matthew away for
even a part of the year, responsibility would fall very heavily on Dick, and
things were far from satisfactory. A spreading sense of loneliness
encompassed Dick. He tried to satisfy himself in the children, but an hour’s
play with them, refreshing and delightful as it was, did not give him all he
sought or all he needed. Gradually there came silent moods in which he
spent most of his hours of relaxation and which were only broken by a
plunge into business or into the midst of some noisy party at which Cecily
might or might not join him. It did not matter whether she did or not. He
was tied to the sense of her instinctive criticism of many of the things he
liked and she to her sense of failure.
They were both much interested in Matthew’s campaign. That gave them
something to talk about and something to focus a mutual interest upon. But
Cecily was suffering even more from a fear of Matthew’s departure than
was Dick. Since her mother had died, she, like Dick, had been lonely, but
that did not help them to find refuge in each other. Matthew and, curiously
enough, Ellen, were the only people in whom Cecily felt there was
comprehension of her and approval. She had one conversation with Mother
Fénelon when she and Dick reached the breaking point.
“There’s no reason for this,” said Mother Fénelon. “You are a good
woman and your husband is a good man. You have duties to each other.”
“Virtue and duties are the least part of marriage to-day, Mother Fénelon.
You can’t manage with just those things. You have to use the modern
methods. It’s a science to-day to have a husband.”
“Marriage is what it always has been.”
“I’m afraid not. It’s altered with the jazz band and the servant problem
and the ‘keep young’ crusade.”
There was more, but to no purpose. The break came immediately after
Matthew’s election. Reaction helped perhaps, as did the fact that little by
little every one had come to guess that the young Harrisons were unhappy
and Della and Madeline and others had come to give Cecily advice.
“You’ve humiliated me beyond all decency,” Cecily told Dick bitterly.
“There’s no dignity, no privacy left between us.”
“Then I’d better go,” answered Dick.
She weakened then, but it was all useless and in her mind she knew that
Dick must go, that they could not keep on this rending life, which was
exhausting them both. Dick went to his club. He wanted to leave the city,
but with Matthew’s departure imminent he couldn’t. And with Dick’s
definite action bruited about, the young Harrisons became the favorite topic
for discussion—discussion which carried its probing back to tales of the
first unhappy marriage of Mrs. Warner and made strange and foolish
deductions.
Mr. Warner, after listening for an hour to Della, who brought the news
home and philosophized extempore on just what Cecily’s mistake had been,
took his hat and proceeded to Cecily’s house. It was the day on which the
few personal effects which Dick needed had left the house. She met her
stepfather in the living-room, rising from a dusky corner where she was
sitting with her hands in her lap, strangely idle. The soft white silk of her
dress was hardly whiter than her face.
Mr. Warner put his hat and cane down slowly and went towards her,
taking both her hands.
“My poor Cecily.”
She did not show any sign of collapse or tears. It seemed to him that she
was broken, but the impression did not come from her appearance or her
voice.
“Dick thought he’d better go.”
He sat down and tapped on the arms of his chair, an old man habit that
had come over him lately.
“Do you want a divorce from Dick, Cecily?”
“Not now. Neither of us wants that now. We’re too—raw.” She
shuddered.
“And you’re going to live here alone?”
“Here, with the children.”
“How is Dick going to do without the children?”
“I think he can. He can’t bear living with me for the sake of them and I
must have them.”
“Ah, Cecily, this won’t last. You and Dick are a pair of naughty children.
I’ve a notion to go down to the club and bring him home by the ear.”
Cecily stiffened. “Promise me you won’t do anything like that! Don’t
make it begin all over again now. We’ve tried and tried, and we can’t.”
“But what is it? Is this nonsense Della talks about Dick’s wanting to go
out more and your refusing the actual reason you’ve dared to break up your
home?”
“That’s what people will say,” answered Cecily, “but of course that’s just
a symptom of what’s the matter with us. The trouble is that we don’t think
marriage means the same thing; we don’t mean the same thing by it. And
every outward expression of my idea jars on him—and his on me. We’ve
become angry and furtive and quarrelsome and condemning.”
“And yet I’ll bet you will be reconciled within a month. Perhaps sooner.
It may be that this little separation is just what you both need to straighten
out all this trouble.”
“Reconciled! Reconciled!” repeated Cecily. “We’ve been reconciled a
dozen times in the past year. No, father, that won’t do it.”
He sat silent for a while and she watched from the window in a strange,
still way.
“It’s not right nor necessary. I wish your mother were here.”
“I wouldn’t like her to see me a failure,” said Cecily with that note of
complete depression.
“Don’t be foolish. You’re not a failure. How could any one with three
fine, husky children be a failure?”
“It’s not enough to make success.”
She rose after a little and offered him a cigar.
“Some Dick left.”
“He’ll be back after them,” said Mr. Warner.
She smiled, but it was a tragic little smile.
“You’ll have to smile better than that for the children.”
“I will—for them.”
“Then why not for Dick?”
“Dick doesn’t care for me.”
“Dick does.”
She gave the dreariest little gesture of negation.
“You and your mother are curiously alike, Cecily.”
“No.”
“I have often wondered,” he went on ruminatively after a moment, “if
there wasn’t something of a case for Allgate Moore. Of course he treated
your mother badly. She never even told me about it, but we all knew. After I
married your mother—and I was an older man with somewhat cool
judgments, my share of discretion and years of experience—I wondered
about him sometimes. Because I had a hard time understanding your mother
and a hard time being good to her.”
“But you were good to her.”
“After I had learned how; after I had studied and planned how, so that I
might not shock her or frighten her or disgust her or hurt her. You are like
her—fastidious, delicate minded, not delicate only in mood, but delicate
always. You like fine things and beautiful things. So do most men, but most
men like other things too. Your mother could not tolerate in any one what
was unbeautiful or coarse—many human things.”
“But she could, for she told me to be tolerant.”
Mr. Warner moved a little in the shadow which had fallen on his chair.
“That’s what I taught her,—what I tried to teach her so that contacts
would not be too hard for her.”
“What if contacts are hard? Isn’t it better to preserve truth, to live
according to beauty—not to be cheap? I know how silly, how common it all
sounds, will sound; the things they will say about Dick and me. But it isn’t
true that trivialities have made the trouble. It’s big things, basic things. I
don’t want to compromise with an age that seems all wrong in its standards.
I can’t bear to form myself on people like Della and Fliss.”
“It wouldn’t do you any good to try that,” said Mr. Warner with a
chuckle, “but I wish, my dear, that your humor was a little nearer the
surface and that it could come to your assistance when you are unhappy as
well as when you are happy.”
“It’s queer about that. I can only see things black and white—happy or
sad. It’s a great drawback. Sometimes I try to pretend, but it’s always so
easy to see through my pretense.”
Mr. Warner was pursuing his previous line of thought.
“You and your mother are such women as foster the ideals men have
about women—if they have any—making ideals for the home which every
man treasures or respects. But it’s hard for men to live by their ideals alone
and you demand that.”
“I don’t understand it at all,” said Cecily, wearily, “why an effort to keep
things close to the ideal men promise you before they marry you should end
in failure.”
“If it is failure; but I don’t believe it is. I don’t think you’ve hit the real
reason for it. Cecily, is there any third person involved in this?”
“Woman, you mean?”
He nodded.
“Not in the way you mean. We disagree awfully over one woman whom
Dick admires,—Fliss Allenby.”
“He’s not in love with her.”
“No. That makes it all the worse. If he were you could understand his
taking up her defense every time a criticism of her is made. But as a matter
of fact he prefers even her—for whom he doesn’t care and whom I can
remember his scorning when I first took her up after we were married—to
me. He prefers almost anything to me.”
“Don’t get bitter, Cecily.”
“I didn’t know what that word meant except abstractly seven years ago.
Now it seems to express me.”
“Nonsense. Turn on the lights, my dear. We’re too gloomy.”
The conversation became more practical.
“Have you made any money arrangement with Dick?”
“I don’t want any money from Dick. If he’s not living with me, I don’t
want his money. I couldn’t bear to touch it.”
“That’s quixotic, my dear, but if you won’t take his, you must let me
help.”
“I’ve a little of my own, you know,” said Cecily.
“As I remember, very little.”
“Three thousand a year. Lots of people live on that.”
“How much have you and Dick been spending?”
“About twenty-five thousand. But that was with cars and all sorts of
luxuries. We’ll just do without those and I won’t need new clothes for a
long time, nor will the children.”
“And when you do?”
“Well, we’ll have to do without them. Or maybe I could earn some
money. Anyway I will not touch Dick’s money and I won’t take yours
either, father, please. I couldn’t let you support me—and Della.”
“Cecily!”
“That was horrid, wasn’t it? Well, please let me get along as best I can.
Let me be honest with myself.”
“You are making it so hard for Dick.”
“Yes. He seemed to take that part much harder than any other. It was the
only thing that really seemed to worry him—not to be able to salve things
over with money. If he sends me money, I shall send it back.”
Mr. Warner rose.
“I’m going now, my dear. I can’t tell you how sorry I am about this or
how convinced I am that it won’t last. I want you to let me help you. I want
to come and talk to you now and then.”
“Yes, please do that. I shall be lonely once in a while,” she said bravely.
“You don’t mind all the silly talk?”
Cecily shrugged. “I shan’t hear it. No, I don’t think I do, except for Dick
a little.”
“Would you like to go away for the rest of the year?”
“I thought of that, but it doesn’t seem wise to take the children away just
now. And that, too, would be expensive.”
Mr. Warner went down the street slowly, tapping the darkened pavement
with his cane.

“I don’t care to discuss it, Fliss. It’s none of our business.”


“I hope not,” said Fliss.
Matthew frowned at her and she laughed at him.
“You should see the frantic interest of people whose business it most
certainly is not.”
“That’s easy to imagine,” he answered. “But I don’t care to be in their
class.”
She went on, “Cecily, you know, who has been really not of paramount
interest to any one lately, is now the real center of thought. Why she did and
why he didn’t and what was the matter and how long it has been going on
and if Dick’s stenographer is really involved or if it’s Cecily’s iceman——”
“Spare me that stuff, Fliss.”
“I haven’t been spared. I’ve had it all day. But seriously, Matthew, what
is the matter with that fool girl? Why doesn’t she appreciate what she’s
got?”
“Does he appreciate what he’s got?”
“United States Senator judicial temperament bound to see both sides.
Well, why doesn’t some one open both the kittens’ eyes if they can’t
appreciate each other?”
He turned to look at her. “You’re pleased about all this, aren’t you?”
“Well, perhaps just a little satisfied in my heart. Cecily made me the butt
of the town for weeks with that Ellen stuff. Do you blame me for a little
human nature?”
“I don’t blame you for anything, Fliss. I accept you.”
“And Cecily?”
“I said that was none of our business.”
“Then why spend so long composing notes to her last night?”
He looked at her accusingly.
“In the wastebasket, my dear. I don’t always go over it, but I was so
interested. Evidently you hadn’t gone very far with any of the notes.”
“Once in a while I think that nothing but a spanking, Fliss——”
“Wife-beater!”
“I’ll write my notes downtown after this, you know.”
“I suppose so. I’ll have to bribe the janitor to save me the wastebaskets.
Well, if you won’t talk about Cecily, let’s talk about Washington. I get a
little weak in the knees when I think of all I’ll have to learn. I don’t mean to
get too many clothes, either. But the ones I do get——”
“I was wondering if I hadn’t better go on alone at first. I could get a bit
adjusted and I can’t see how you can leave your mother.”
Her face clouded. “I know, Matthew. I seem a heartless brute, but there’s
nothing I can do; and she gets so irritated at me now; and whenever I go
there and try to do anything she and Mrs. Ellis are hobnobbing over horrors
in that dreadful way and everything is so awful. Matthew, don’t leave me
with them!”
“Why, no, you’d have your own house. It would only be for a little
while. But I’ll take you if you want to go so badly. I do get a little sorry for
your father. He’s——”
“But I tell you there’s nothing I can do for him. I have tried! But I can’t
sit through endless hours of moving pictures and silence.”
“Well, dear, you can’t help if you feel like that. It is probably true you
could do nothing.”
“Where are you going to-night?”
“Going to work unless you need me.”
“No, I told Polly Angell that I thought you couldn’t come to dinner and
she asked me to come anyway. She found an extra man.”
“Ames?”
Fliss nodded.
“You ought to leave him alone. What do you get out of it?”
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

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.

Let us accompany you on the journey of exploring knowledge and


personal growth!

ebookmass.com

You might also like