1. Javascript Essentials For Dummies Paul Mcfedries
download
https://ebookbell.com/product/javascript-essentials-for-dummies-
paul-mcfedries-56582028
Explore and download more ebooks at ebookbell.com
2. Here are some recommended products that we believe you will be
interested in. You can click the link to download.
Javascript Essentials For Dummies 1st Edition Paul Mcfedries
https://ebookbell.com/product/javascript-essentials-for-dummies-1st-
edition-paul-mcfedries-57572884
Javascript Essentials For Sap Abap Developers A Guide To Mobile And
Desktop Application Development 1st Edition Rehan Zaidi Auth
https://ebookbell.com/product/javascript-essentials-for-sap-abap-
developers-a-guide-to-mobile-and-desktop-application-development-1st-
edition-rehan-zaidi-auth-5880832
Mootools Essentials The Official Mootools Reference For Javascript And
Ajax Development Aaron Newton
https://ebookbell.com/product/mootools-essentials-the-official-
mootools-reference-for-javascript-and-ajax-development-aaron-
newton-5471546
Mastering Javascript Design Patterns Essential Solutions For Effective
Javascript Web Design 3rd Edition Timms
https://ebookbell.com/product/mastering-javascript-design-patterns-
essential-solutions-for-effective-javascript-web-design-3rd-edition-
timms-22137368
3. Essential Cryptography For Javascript Developers A Practical Guide To
Leveraging Common Cryptographic Operations In Nodejs And The Browser
1st Edition Alessandro Segala
https://ebookbell.com/product/essential-cryptography-for-javascript-
developers-a-practical-guide-to-leveraging-common-cryptographic-
operations-in-nodejs-and-the-browser-1st-edition-alessandro-
segala-53025618
Essential Cryptography For Javascript Developers A Practical Guide To
Leveraging Common Cryptographic Operations In Nodejs And The Browser
Alessandro Segala
https://ebookbell.com/product/essential-cryptography-for-javascript-
developers-a-practical-guide-to-leveraging-common-cryptographic-
operations-in-nodejs-and-the-browser-alessandro-segala-58531630
Simplified Javascript For Very Important Programmers The Fast Track To
Mastering Essential Javascript Concepts 20230310 Ebenezer Don
https://ebookbell.com/product/simplified-javascript-for-very-
important-programmers-the-fast-track-to-mastering-essential-
javascript-concepts-20230310-ebenezer-don-48134224
Javascript Essentials 1st Edition Smashing Magazine
https://ebookbell.com/product/javascript-essentials-1st-edition-
smashing-magazine-4541770
Javascript And Json Essentials Sai Srinivas Sriparasa
https://ebookbell.com/product/javascript-and-json-essentials-sai-
srinivas-sriparasa-4653734
6. JavaScript® Essentials For
Dummies®
To view this book's Cheat Sheet,
simply go to www.dummies.com and
search for “JavaScript Essentials For
Dummies Cheat Sheet” in the Search
box.
Table of Contents
Cover
Title Page
Copyright
Introduction
About This Book
Foolish Assumptions
Icons Used in This Book
Where to Go From Here
Chapter 1: JavaScript: The Big Picture
Adding JavaScript Code to a Web Page
What You Need to Get Started
Dealing with Two Exceptional Cases
Commenting Your Code
Moving to External JavaScript Files
Chapter 2: Programming with Variables
7. Getting Your Head around Variables
Naming Variables: Rules and Best Practices
Understanding Literal Data Types
Chapter 3: Building Expressions
Understanding How Expressions Are Structured
Creating Numeric Expressions
Building String Expressions
Building Comparison Expressions
Building Logical Expressions
Understanding Operator Precedence
Chapter 4: Controlling the Flow of JavaScript
Decision-Making with if Statements
Branching with if…else Statements
Understanding the Value of Code Looping
Working with while Loops
Working with for Loops
Working with do…while Loops
Chapter 5: Harnessing the Power of Functions
Getting to Know the Function Structure
Making a Function Call
Passing One or More Values to a Function
Getting a Value from a Function
Working with Anonymous Functions
Working with Arrow Functions
Chapter 6: Coding the Document Object Model
Getting Familiar with Objects
Introducing the Document Object Model
Specifying Elements in Your Code
Touring the DOM with Code
Adding, Modifying, and Removing Elements
Using Code to Mess Around with CSS
Using Code to Tweak HTML Attributes
8. Listening for Page Events
Chapter 7: Working with Arrays
What Is an Array?
Declaring an Array
Populating an Array
Iterating Arrays
Manipulating Arrays
Chapter 8: Coding Strings and Dates
Manipulating Strings
Dealing with Dates and Times
Chapter 9: Debugging JavaScript
Laying Out Your Debugging Tools
Debugging 101: Using the Console
Putting Your Code into Break Mode
Stepping Through Your Code
Chapter 10: Dealing with Form Data
Coding Text Fields
Programming Checkboxes
Coding Radio Buttons
Programming Selection Lists
Working with Form Events
Handling Form Data
Chapter 11: Ten JavaScript Debugging Strategies
Get Thee to Your Dev Tools
The Console Is Your Best Debugging Friend
Give Your Code a Break(point)
Step Through Your Code
Monitor Variable and Object Property Values
Indent Your Code
Break Down Complex Tasks
Break Up Long Statements
Comment Out Problem Statements
9. Use Comments To Document Your Scripts
Index
About the Author
Advertisement Page
Connect with Dummies
End User License Agreement
List of Tables
Chapter 2
TABLE 2-1 Common JavaScript Escape Sequences
Chapter 3
TABLE 3-1 The JavaScript Arithmetic Operators
TABLE 3-2 The JavaScript Arithmetic Assignment Operators
TABLE 3-3 The JavaScript Comparison Operators
TABLE 3-4 The JavaScript Logical Operators
TABLE 3-5 The JavaScript Order of Precedence for Operators
Chapter 7
TABLE 7-1 Useful Array Methods
Chapter 8
TABLE 8-1 String Object Methods for Searching for Substrings
TABLE 8-2 String Object Methods for Extracting Substrings
TABLE 8-3 Arguments Associated with the Date Object
TABLE 8-4 Date Object Methods That Extract Date Values
TABLE 8-5 Date Object Methods That Set Date Values
List of Illustrations
Chapter 1
10. FIGURE 1-1: This “alert” message appears when you open the
HTML file containing...
FIGURE 1-2: When you open the file, the text displays the date
and time the fil...
FIGURE 1-3: This page uses an external JavaScript file to display a
footer mess...
Chapter 2
FIGURE 2-1: The browser substituting the current value of a
variable.
FIGURE 2-2: The script first prompts for the user’s first name.
FIGURE 2-3: The script then uses the name to display a
personalized welcome mes...
FIGURE 2-4: Using the n escape sequence enables you to format
text so that it ...
Chapter 4
FIGURE 4-1: Set up your while expression so that the prompting
stops when the u...
FIGURE 4-2: This script uses the current value of the counter
variable to custo...
FIGURE 4-3: The decrementing value of the rank variable is used
to create a rev...
Chapter 5
FIGURE 5-1: An example of calling a function when the <script>
tag is p...
FIGURE 5-2: An example of calling a function after the page has
loaded.
FIGURE 5-3: An example of calling a function in response to an
event.
FIGURE 5-4: The output includes the return value of the custom
function calcula...
Chapter 6
FIGURE 6-1: This script displays the document.location property in a
console me...
FIGURE 6-2: The web page code as a hierarchy.
FIGURE 6-3: The output of the script that iterates over the div
elements.
11. FIGURE 6-4: The value of the bodyChildElements variable displayed
in the consol...
FIGURE 6-5: This code uses the add() method to add the class
named my-class to ...
FIGURE 6-6: The click event callback function adds some HTML
and text to the di...
FIGURE 6-7: The keypress event callback function uses e.which to
write the nume...
Chapter 9
FIGURE 9-1: The HTML viewer, such as Chrome’s Elements tab,
enables you to insp...
FIGURE 9-2: When you invoke break mode, the web browser
displays its debugging ...
FIGURE 9-3: In the browser’s debugging tool, click a line number
to set a break...
Chapter 10
FIGURE 10-1: The script converts the input element’s default text
to all-lowerc...
FIGURE 10-2: A form used to gather user settings for the page.
14. INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OF MERCHANTABILITY OR FITNESS
FOR A PARTICULAR PURPOSE. NO WARRANTY MAY
BE CREATED OR EXTENDED BY SALES
REPRESENTATIVES, WRITTEN SALES MATERIALS OR
PROMOTIONAL STATEMENTS FOR THIS WORK. THE
FACT THAT AN ORGANIZATION, WEBSITE, OR
PRODUCT IS REFERRED TO IN THIS WORK AS A
CITATION AND/OR POTENTIAL SOURCE OF
FURTHER INFORMATION DOES NOT MEAN THAT
THE PUBLISHER AND AUTHORS ENDORSE THE
INFORMATION OR SERVICES THE ORGANIZATION,
WEBSITE, OR PRODUCT MAY PROVIDE OR
RECOMMENDATIONS IT MAY MAKE. THIS WORK IS
SOLD WITH THE UNDERSTANDING THAT THE
PUBLISHER IS NOT ENGAGED IN RENDERING
PROFESSIONAL SERVICES. THE ADVICE AND
STRATEGIES CONTAINED HEREIN MAY NOT BE
SUITABLE FOR YOUR SITUATION. YOU SHOULD
CONSULT WITH A SPECIALIST WHERE
APPROPRIATE. FURTHER, READERS SHOULD BE
AWARE THAT WEBSITES LISTED IN THIS WORK MAY
HAVE CHANGED OR DISAPPEARED BETWEEN WHEN
THIS WORK WAS WRITTEN AND WHEN IT IS READ.
NEITHER THE PUBLISHER NOR AUTHORS SHALL BE
LIABLE FOR ANY LOSS OF PROFIT OR ANY OTHER
COMMERCIAL DAMAGES, INCLUDING BUT NOT
LIMITED TO SPECIAL, INCIDENTAL,
CONSEQUENTIAL, OR OTHER DAMAGES.
For general information on our other products and
services, please contact our Customer Care Department
within the U.S. at 877-762-2974, outside the U.S. at 317-
572-3993, or fax 317-572-4002. For technical support,
please visit https://hub.wiley.com/community/support/dummies.
15. Wiley publishes in a variety of print and electronic
formats and by print-on-demand. Some material included
with standard print versions of this book may not be
included in e-books or in print-on-demand. If this book
refers to media such as a CD or DVD that is not included
in the version you purchased, you may download this
material at http://booksupport.wiley.com. For more
information about Wiley products, visit www.wiley.com.
Library of Congress Control Number: 2024933533
ISBN 978-1-394-26321-9 (pbk); ISBN 978-1-394-26323-3
(ebk); ISBN 978-1-394-26322-6 (ebk)
16. Introduction
HTML and CSS are awesome technologies, and you can
use them to create pages that look amazing. But after
you funnel your page to your web server and look at it a
few (dozen) times, you may notice a subtle feeling of
disappointment creeping in. Why? It can be hard to pin
down, but that hint of dismay comes from a stark fact:
Your web page just kind of sits there.
Sure, you probably have a link or three to click, but most
likely those links just take you to more of your pages that
also just kind of sit there. Or maybe a link takes you to
another site altogether, one that feels dynamic and alive
and interactive. Ah, engagement! Ooh, excitement!
What’s the difference between a page that does nothing
and a page that seems to be always dancing? One word:
JavaScript. If you want your pages to be dynamic and
interactive, you need a bit of behind-the-scenes
JavaScript to make it so.
“But,” I hear you object, “HTML isn’t that hard to learn.
JavaScript is a programming language, for crying out
loud!” I hear you. It’s true that anyone can learn HTML
as long as they start with the basic tags, examine lots of
examples of how they work, and slowly work their way
up to more complex pages. It’s just a matter of creating a
solid foundation and then building on it.
I’m convinced that JavaScript can be approached in
much the same way. I’m certainly not going to tell you
that JavaScript is as easy to learn as HTML. That would
be a bald-faced lie. However, I will tell you that there is
nothing inherently difficult about JavaScript. I believe
that if you begin with the basic syntax and rules, study
tons of examples to learn how they work, and then slowly
17. build up to more complex scripts, you can learn
JavaScript programming. I predict here and now that by
the time you finish this book, you’ll even be a little bit
amazed at yourself and at what you can do.
About This Book
Welcome, then, to JavaScript Essentials For Dummies.
This book gives you a solid education on the standard
programming language underlying the World Wide Web.
You learn how to set up the tools you need and, given
any web pages you have (or someone else has) built with
HTML and CSS, you learn how to use JavaScript to
program those pages. My goal is to show you that adding
a sprinkling of JavaScript magic to a page isn’t hard to
learn, and that even the greenest rookie programmer can
learn how to create dynamic and interactive web pages
that will amaze their family and friends (and
themselves).
If you’re looking for lots of programming history,
computer science theory, and long-winded explanations
of concepts, I’m sorry, but you won’t find it here. My
philosophy throughout this book comes from Linus
Torvalds, the creator of the Linux operating system:
“Talk is cheap. Show me the code.” I explain what needs
to be explained and then I move on without further ado
(or, most of the time, without any ado at all) to examples
and scripts that do more to illuminate a concept that any
verbose explanations I could muster (and believe me, I
can muster verbosity with the best of them).
Foolish Assumptions
This book is not a primer on the internet or on using the
World Wide Web. This is a book on coding web pages,
18. pure and simple. This means I assume the following:
You know how to operate a basic text editor, and how
to get around the operating system and file system on
your computer.
You have an internet connection.
You know how to use your web browser.
You know the basics of HTML and CSS.
Yep, that’s it.
Icons Used in This Book
This icon points out juicy tidbits that are likely to
be repeatedly useful to you — so please don’t forget
them.
Think of these icons as the fodder of advice
columns. They offer (hopefully) wise advice or a bit
more information about a topic under discussion.
Look out! In this book, you see this icon when I’m
trying to help you avoid mistakes that can cost you
time, money, or embarrassment.
Where to Go From Here
19. How you approach this book depends on your current
level of coding and/or JavaScript expertise (or lack
thereof):
If you’ve never programmed before, begin at the
beginning with Chapter 1 and work at your own pace
sequentially through Chapters 2, 3, 4, and 5. This will
give you all the knowledge you need to pick and
choose what you want to learn throughout the rest of
the book.
If you’ve done some non-JavaScript programming,
start with Chapter 1, skim through Chapters 2 through
5 to see how JavaScript does the standard
programming tasks, and then pick and choose your
topics from there.
If you’ve done some JavaScript coding already, I
suggest working quickly through the material in
Chapters 2 through 5, and then diving into the all-
important material on the Document Object Model in
Chapter 6. From there, you can peruse the rest of the
chapters as you see fit.
20. Chapter 1
JavaScript: The Big Picture
IN THIS CHAPTER
Getting a feel for programming in general, and
JavaScript in particular
Checking out the tools you need to get coding
Adding comments to your JavaScript code
Storing your code in a separate JavaScript file
In this chapter, you explore some useful JavaScript
basics. Don’t worry if you’ve never programmed before. I
take you through everything you need to know, step-by-
step, nice and easy. As you’re about to find out, it really
is fun to program.
Adding JavaScript Code to
a Web Page
Okay, it’s time to roll up your sleeves, crack your
knuckles, and start coding. This section describes the
standard procedure for constructing and testing a script
and takes you through a couple of examples.
The <script> tag
The basic container for a script is, naturally enough, the
HTML <script> tag and its associated </script> end tag:
<script>
JavaScript statements go here
</script>
21. Where do you put the <script> tag?
With certain exceptions, it doesn’t matter a great deal
where you put your <script> tag. Some people place the
tag between the page’s </head> and <body> tags. The
HTML standard recommends placing the <script> tag
within the page header (that is, between <head> and
</head>), so that’s the style I use in this book:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Where do you put the script tag?</title>
<script>
JavaScript statements go here
</script>
</head>
<body>
</body>
</html>
Here are the exceptions to the put-your-script-anywhere
technique:
If your script is designed to write data to the page, the
<script> tag must be positioned within the page body
(that is, between the <body> and </body> tags) in the
exact position where you want the text to appear.
If your script refers to an item on the page (such as a
form object), the script must be placed after that item.
With many HTML tags, you can add one or more
JavaScript statements as attributes directly within the
tag.
It’s perfectly acceptable to insert multiple <script>
tags within a single page, as long as each one has a
22. corresponding </script> end tag, and as long as you
don’t put one <script> block within another one.
Example #1: Displaying a message
to the user
You’re now ready to construct and try out your first
script. This example shows you the simplest of all
JavaScript actions: displaying a basic message to the
user. The following code shows the script within an
HTML file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Displaying a Message to the User</title>
<script>
alert("Hello JavaScript World!");
</script>
</head>
<body>
</body>
</html>
As shown in here, place the script within the header of a
page, save the file, and then open the HTML file within
your browser.
This script consists of just a single line:
alert("Hello JavaScript World!");
This is called a statement, and each statement is
designed to perform a single JavaScript task. Your
scripts will range from simple programs with just a few
statements to huge projects consisting of hundreds of
statements.
You may be wondering about the semicolon (;) that
appears at the end of the statement. Good eye. You use
the semicolon to mark the end of each of your JavaScript
statements.
23. In the example, the statement runs the JavaScript alert()
method, which displays to the user whatever message is
enclosed within the parentheses (which could be a
welcome message, an announcement of new features on
your site, an advertisement for a promotion, and so on).
Figure 1-1 shows the message that appears when you
open the file.
FIGURE 1-1: This “alert” message appears when you open the HTML file
containing the example script.
How did the browser know to run the JavaScript
statement? When a browser processes (parses, in the
vernacular) a page, it basically starts at the beginning of
the HTML file and works its way down, one line at a
time. If it trips over a <script> tag, it knows one or more
JavaScript statements are coming, and it automatically
executes those statements, in order, as soon as it reads
them. The exception is when JavaScript statements are
enclosed within a function, which I explain in Chapter 5.
One of the cardinal rules of JavaScript
programming is “one statement, one line.” That is,
each statement must appear on only a single line,
and there should be no more than one statement on
each line. I said “should” in the second part of the
24. previous sentence because it is possible to put
multiple statements on a single line, as long as you
separate each statement with a semicolon (;). There
are rare times when it’s necessary to have two or
more statements on one line, but you should avoid it
for the bulk of your programming because multiple-
statement lines are difficult to read and to
troubleshoot.
Example #2: Writing text to the
page
One of JavaScript’s most powerful features is the
capability to write text and even HTML tags and CSS
rules to the web page on-the-fly. That is, the text (or
whatever) gets inserted into the page when a web
browser loads the page. What good is that? For one
thing, it’s ideal for time-sensitive data. For example, you
may want to display the date and time that a web page
was last modified so that visitors know how old (or new)
the page is. Here’s some code that shows just such a
script:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Writing Data to the Page</title>
</head>
<body>
This is a regular line of text.<br>
<script>
document.write("Last modified: " + document.lastModified)
</script>
<br>This is another line of regular text.
</body>
</html>
Notice how the script appears within the body of the
HTML document, which is necessary whenever you want
to write data to the page. Figure 1-2 shows the result.
25. FIGURE 1-2: When you open the file, the text displays the date and time the
file was last modified.
This script makes use of the documentobject, which is a
built-in JavaScript construct that refers to whatever
HTML file (document) the script resides in (check out
Chapter 6 for more about the document object). The
document.write() statement tells the browser to insert
whatever is within the parentheses to the web page. The
document.lastModified portion returns the date and time
the file was last changed and saved.
What You Need to Get
Started
One of the nicest things about HTML and CSS is that the
hurdles you have to leap to get started are not only short
but few in number. In fact, you really need only two
things, both of which are free: a text editor to enter the
text, tags, and properties; and a browser to view the
results. (You’ll also need a web server to host the
finished pages, but the server isn’t necessary when
you’re creating the pages.) Yes, there are high-end text
editors and fancy graphics programs, but these fall into
the “Bells and Whistles” category; you can create
perfectly respectable web pages without them.
The basic requirements for JavaScript programming are
exactly the same as for HTML: a text editor and a
26. browser. Again, programs are available to help you write
and test your scripts, but you don’t need them.
Dealing with Two
Exceptional Cases
In this book, I make a couple of JavaScript assumptions
related to the people who’ll be visiting the pages you
post to the web:
Those people have JavaScript enabled in their web
browser.
Those people are using a relatively up-to-date version
of a modern web browser, such as Chrome, Edge,
Safari, or Firefox.
These are pretty safe assumptions, but it pays to be a bit
paranoid and wonder how you may handle the teensy
percentage of people who don’t pass one or both tests.
Handling browsers with JavaScript
turned off
You don’t have to worry about web browsers not being
able to handle JavaScript, because all modern browsers
have supported JavaScript for a very long time. You may,
however, want to worry about people who don’t support
JavaScript. Although rare, some folks have turned off
their browser’s JavaScript functionality. Why would
someone do such a thing? Many people disable
JavaScript because they’re concerned about security,
they don’t want cookies written to their hard drives, and
so on.
To handle these iconoclasts, place the <noscript> tag
within the body of the page:
27. <noscript>
<p>
Hey, your browser has JavaScript turned off!
</p>
<p>
Okay, cool, perhaps you'll prefer this <a
href="no-js.html">non-JavaScript version</a> of
the page.
</p>
</noscript>
If the browser has JavaScript enabled, the browser
doesn’t display any of the text within the <noscript> tag.
However, if JavaScript is disabled, the browser displays
the text and tags within the <noscript> tag to the user.
To test your site with JavaScript turned off, here are the
techniques to use in some popular browsers:
Chrome (desktop): Open Settings, click Privacy and
Security, click Site Settings, click JavaScript, and then
select the Don’t Allow Sites to Use JavaScript option.
Chrome (Android): Open Settings, tap Site Settings,
tap JavaScript, and then tap the JavaScript switch to
off.
Edge: Open Settings, click the Settings menu, click
Cookies and Site Permissions, click JavaScript, and
then click the Allowed switch to off.
Safari (macOS): Open Settings, click the Advanced
tab, select the Show Develop Menu in Menu Bar, and
then close Settings. Choose Develop ⇒ Disable
JavaScript.
Safari (iOS or iPadOS): Open Settings, tap Safari,
tap Advanced, and then tap the JavaScript switch to
off.
Firefox (desktop): In the Address bar, type
about:config and press Enter or Return. If Firefox
28. displays a warning page, click Accept the Risk and
Continue to display the Advanced Preferences page. In
the Search Preference Name box, type javascript. In
the search results, look for the javascript.enabled
preference. On the far right of that preference, click
the Toggle button to turn the value of the preference
from true to false.
Handling very old browsers
In this book, you learn the version of JavaScript called
ECMAScript 2015, also known as ECMAScript 6, or just
ES6. Why this version, in particular, and not any of the
later versions? Two reasons:
ES6 has excellent browser support, with more than 98
percent of all current browsers supporting the features
released in ES 6. Later versions of JavaScript have less
support.
ES6 has everything you need to add all kinds of useful
and fun dynamic features to your pages. Unless you’re
a professional programmer, the features released in
subsequent versions of JavaScript are way beyond
what you need.
Okay, so what about that couple of percent of browsers
that don’t support ES6?
First, know that the number of browsers that choke on
ES6 features is getting smaller every day. Sure, it’s 2
percent now (about 1.7 percent, actually), but it will be 1
percent in six months, a 0.5 percent in a year, and so on
until the numbers just get too small to measure.
Second, the percentage of browsers that don’t support
ES6 varies by region (it’s higher in many countries in
Africa, for example) and by environment. Most of the
29. people running browsers that don’t fully support ES6 are
using Internet Explorer 11, and most of those people are
in situations in which they can’t upgrade (some
corporate environments, for example).
If luck has it that your web pages draw an inordinate
share of these older browsers, you may need to eschew
the awesomeness of ES6 in favor of the tried-and-true
features of ECMAScript 5. To that end, as I introduce
each new JavaScript feature, I point out those that
arrived with ES6 and let you know if there’s a simple
fallback or workaround (known as a polyfill in the
JavaScript trade) if you prefer to use ES5.
Commenting Your Code
A script that consists of just a few lines is usually easy to
read and understand. However, your scripts won’t stay
that simple for long, and these longer and more complex
creations will be correspondingly more difficult to read.
(This difficulty will be particularly acute if you’re looking
at the code a few weeks or months after you first coded
it.) To help you decipher your code, it’s good
programming practice to make liberal use of comments
throughout the script. A comment is text that describes
or explains a statement or group of statements.
Comments are ignored by the browser, so you can add as
many as you deem necessary.
For short, single-line comments, use the double-slash
(//). Put the // at the beginning of the line, and then type
your comment after it. Here’s an example:
// Display the date and time the page was last modified
document.write("This page was last modified on " + document.lastModified);
You can also use // comments for two or three lines of
text, as long as you start each line with //. If you have a
30. comment that stretches beyond that, however, you’re
better off using multiple-line comments that begin with
the /* characters and end with the */ characters. Here’s
an example:
/*
This script demonstrates JavaScript's ability
to write text to the web page by using the
document.write() method to display the date
and time the web page file was last modified.
This script is Copyright Paul McFedries.
*/
Although it’s fine to add quite a few comments
when you’re just starting out, you don’t have to add a
comment to everything. If a statement is trivial or its
purpose is glaringly obvious, forget the comment and
move on.
Moving to External
JavaScript Files
Earlier in this chapter, I talk about adding JavaScript
code to a web page by inserting the <script> and </script>
tags into the page header (that is, between the <head> and
</head> tags), or sometimes into the page body (that is,
between the <body> and </body> tags). You then write your
code between the <script> and </script> tags.
Putting a script inside the page in this way isn’t a
problem if the script is relatively short. However, if your
script (or scripts) take up dozens or hundreds of lines,
your HTML code can look cluttered. Another problem
you may run into is needing to use the same code on
31. multiple pages. Sure, you can just copy the code into
each page that requires it, but if you make changes down
the road, you need to update every page that uses the
code.
The solution to both problems is to move the code out of
the HTML file and into an external JavaScript file.
Moving the code reduces the JavaScript presence in the
HTML file to a single line (as you’ll learn shortly) and
means that you can update the code by editing only the
external file.
Here are some things to note about using an external
JavaScript file:
The file must use a plain text format.
Use the .js extension when you name the file.
Don’t use the <script> tag within the file. Just enter
your statements exactly as you would within an HTML
file.
The rules for when the browser executes statements
within an external file are identical to those used for
statements within an HTML file. That is, statements
outside of functions are executed automatically when
the browser comes across your file reference, and
statements within a function aren’t executed until the
function is called. (Not sure what a “function” is? You
get the full scoop in Chapter 5.)
To let the browser know that an external JavaScript file
exists, add the src attribute to the <script> tag. For
example, if the external file is named myscripts.js, your
<script> tag is set up as follows:
<script src="myscripts.js">
32. This example assumes that the myscripts.js file is in the
same directory as the HTML file. If the file resides in a
different directory, adjust the src value accordingly. For
example, if the myscripts.js file is in a subdirectory
named scripts, you use this:
<script src="scripts/myscripts.js">
You can even specify a file from another site (presumably
your own!) by specifying a full URL as the src value:
<script src="http://www.host.com/myscripts.js">
As an example, the following code shows a one-line
external JavaScript file named footer.js:
document.write("This page is Copyright " + new Date().getFullYear());
This statement writes the text “Copyright” followed by
the current year. (I know: This code looks like some real
gobbledygook right now. Don’t sweat it, because you’ll
learn exactly what’s going on here when I discuss the
JavaScript Date object in Chapter 8.)
The following code shows an HTML file that includes a
reference for the external JavaScript file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Using an External JS File</title>
</head>
<body>
<p>
Regular page doodads go here.
</p>
<hr>
<footer>
<script src="footer.js">
</script>
</footer>
</body>
</html>
33. When you load the page, the browser runs through the
HTML line by line. When it gets to the <footer> tag, it
notices the external JavaScript file that’s referenced by
the <script> tag. The browser loads that file and then
runs the code within the file, which writes the Copyright
message to the page, as shown in Figure 1-3.
FIGURE 1-3: This page uses an external JavaScript file to display a footer
message.
34. Chapter 2
Programming with
Variables
IN THIS CHAPTER
Understanding variables
Assigning names to variables
Introducing JavaScript data types
Figuring out numbers
Stringing strings together
By default, JavaScript programs live a life without short-
term memory. The web browser executes your code one
statement at a time until there are no more statements
left to process. It all happens in the perpetual present.
Ah, but notice that I refer to this lack of short-term
memory as the “default” state of your scripts. It’s not the
only state, so that means things can be different. You
have the power to give your scripts the gift of short-term
memory, and you do that by using handy little chunks of
code called variables. In this chapter, you delve into
variables, which is a fundamental and crucial
programming topic. You investigate what variables are,
what you can do with them, and how to wield them in
your JavaScript code.
Getting Your Head around
Variables
35. Why would a script need short-term memory? Because
one of the most common concepts that crops up when
coding is the need to store a temporary value for use
later on. In most cases, you want to use that value a bit
later in the same script. However, you may also need to
use it in some other script, to populate an HTML form, or
as part of a larger or more complex calculation.
For example, your page may have a button that toggles
the page text between a larger font size and the regular
font size, so you need some way to “remember” that
choice. Similarly, if your script performs calculations,
you may need to set aside one or more calculated values
to use later. For example, if you’re constructing a
shopping cart script, you may need to calculate taxes on
the order. To do that, you must first calculate the total
value of the order, store that value, and then later take a
percentage of it to work out the tax.
In programming, the way you save a value for later use is
by storing it in a variable. A variable is a small area of
computer memory that’s set aside for holding a chunk of
program data. The good news is that the specifics of how
the data is stored and retrieved from memory happen
well behind the scenes, so it isn’t something you ever
have to worry about. As a coder, working with variables
involves just three things:
Creating (or declaring) variables
Assigning values to those variables
Including the variables in other statements in your
code
The next three sections fill in the details.
Declaring a variable with let
36. The process of creating a variable is called declaring in
programming terms. All declaring really means is that
you’re supplying the variable with a name and telling the
browser to set aside a bit of room in memory to hold
whatever value you end up storing in the variable. To
declare a variable in JavaScript, you use the let keyword,
followed by a space, the name of the variable, and the
usual line-ending semicolon. For example, to declare a
variable named interestRate, you use the following
statement:
let interestRate;
Here are a few things to bear in mind when you’re
declaring variables in your scripts:
Declare a variable only once: Although you’re free
to use a variable as many times as you need to within
a script, you declare the variable only once. Trying to
declare a variable more than once will cause an error.
Use a comment to describe each variable:
Variables tend to proliferate to the point where it often
becomes hard to remember what each variable
represents. You can make the purpose of each variable
clear by adding a comment right after the variable
declaration, like so:
let interestRate; // Annual interest rate for loan calculation
Declare each variable before you use it: If you use
a variable before you declare it, you’ll get an error.
In the first two items here, when I say that
you’ll “get an error,” I don’t mean that an error
37. message will pop up on the screen. The only thing
you’ll notice is that your script doesn’t run. To read
the error message, you need to access your browser’s
web development tools, a task I go into in satisfying
detail in Chapter 9.
Declare each variable right before you first use
it: You’ll make your programming and debugging
(refer to Chapter 9) life much easier if you follow this
one simple rule: Declare each variable just before (or
as close as possible to) the first use of the variable.
The let keyword was introduced in ECMAScript
2015 (ES6). If you need to support really old
browsers — I’m looking at you, Internet Explorer 11
and earlier — then use the var keyword instead.
Storing a value in a variable
After your variable is declared, your next task is to give it
a value. You use the assignment operator — the equals
(=) sign — to store a value in a variable, as in this general
statement:
variableName = value;
Here’s an example that assigns the value 0.06 to a
variable named interestRate:
interestRate = 0.06;
Note, too, that if you know the initial value of the
variable in advance, you can combine the declaration
and initial assignment into a single statement, like this:
let interestRate = 0.06;
It’s important to remember that, given a variable
declared with the let keyword, you’re free to change that
38. variable’s value any time you want. For example, if the
value you assign to the interestRate variable is an annual
rate, later on your code may need to work with a monthly
rate, which is the annual rate divided by 12. Rather than
calculate that by hand, just put it in your code using the
division operator (/):
interestRate = 0.06 / 12;
As a final note about using a variable assignment, take a
look at a variation that often causes some confusion
among new programmers. Specifically, you can set up a
statement that assigns a new value to a variable by
changing its existing value. Here’s an example:
interestRate = interestRate / 12;
If you’ve never come across this kind of statement
before, it probably looks a bit illogical. How can
something equal itself divided by 12? The secret to
understanding such a statement is to remember that the
browser always evaluates the right side of the statement
— that is, the expression to the right of the equals sign
(=) — first. In other words, it takes the current value of
interestRate, which is 0.06, and divides it by 12. The
resulting value is what’s stored in interestRate when all is
said and done. For a more in-depth discussion of
operators and expressions, head over to Chapter 3.
Because of this evaluate-the-expression-and-then-
store-the-result behavior, JavaScript assignment
statements shouldn’t be read as “variable equals
expression.” Instead, it makes more sense to think of
them as “variable is set to expression” or “variable
assumes the value given by expression.” Reading
assignment statements this way helps to reinforce
39. the important concept that the expression result is
being stored in the variable.
Checking out another way to declare
a variable: const
The word variable implies that the value assigned to a
variable is allowed to vary, which is the case for most
variables you declare. Most, but not all. Sometimes your
scripts will need to use a value that remains constant.
For example, suppose you’re building a calculator that
converts miles to kilometers. The conversion factor is
1.60934, and that value will remain constant throughout
your script.
It’s good programming practice to store such values in a
variable for easier reading. However, if you use let for
this declaration, you run the risk of accidentally
changing the value somewhere in your code because
variables declared with let can change.
To avoid accidentally changing a value that you want to
remain constant, you can declare the variable using the
const keyword instead. Here’s the general syntax:
const variableName = value;
Note that, unlike with let, you must assign a value to the
variable when you declare it with const. Here’s an
example that declares a variable named milesToKilometers
and assigns it the value 1.60934:
const milesToKilometers = 1.60934;
Are there any real advantages to using const over
let in cases where a variable’s value must never
change? Yep, there are two pretty good ones:
40. Using the const keyword is a reminder that you’re
dealing with a nonchanging value, which helps you to
remember not to assign the variable a new value.
If you do try to change the value of a variable declared
with const, you’ll generate an error, which is another
way to remind you that the variable’s value is not to
be messed with.
Given these advantages, many JavaScript
programmers declare every variable with const and
use let only for the variables that they know will
change. As your code progresses, if you find that a
const variable needs to change, you can go back and
change const to let.
Using variables in statements
With your variable declared and assigned a value, you
can then use that variable in other statements. When the
browser comes across the variable, it goes to the
computer’s memory, retrieves the current value of the
variable, and then substitutes that value into the
statement. The following code presents an example:
let interestRate = 0.06;
interestRate = interestRate / 12;
document.write(interestRate);
This code declares a variable named interestRate with the
value 0.06; it then divides that value by 12 and stores the
result in the variable. The document.write() statement then
displays the current value of the variable, as shown in
Figure 2-1.
41. FIGURE 2-1: The browser substituting the current value of a variable.
The following code shows a slightly different example:
let firstName;
firstName = prompt("Please tell me your first name:");
document.write("Welcome to my website, " + firstName);
This script uses the prompt() method (explained shortly)
to ask the user to enter their first name, as shown in
Figure 2-2. When the user clicks OK, their name is stored
in the firstName variable. The script then uses a
document.write() statement to display a personalized
welcome message using the value of the firstName
variable, as shown in Figure 2-3.
FIGURE 2-2: The script first prompts for the user’s first name.
FIGURE 2-3: The script then uses the name to display a personalized welcome
message.
42. When you need to get data from the user, run the
prompt() method:
prompt(string, default);
Here’s what the various parts are:
string: A string that instructs the user what to enter
into the prompt box.
default: An optional string that specifies the initial
value that appears in the prompt box.
The prompt() method always returns a value:
If the user clicks OK, prompt() returns the value entered
into the prompt text box.
If the user clicks Cancel, prompt() returns null.
Naming Variables: Rules
and Best Practices
If you want to write clear, easy-to-follow, and easy-to-
debug scripts (and who doesn’t?), you can go a long way
toward that goal by giving careful thought to the names
you use for your variables. This section helps by running
through the rules you need to follow and by giving you
some tips and guidelines for creating good variable
names.
Rules for naming variables
JavaScript has only a few rules for variable names:
43. The first character must be a letter or an underscore
(_). You can’t use a number as the first character.
The rest of the variable name can include any letter,
any number, or the underscore. You can’t use any
other characters, including spaces, symbols, and
punctuation marks.
As with the rest of JavaScript, variable names are case
sensitive. That is, a variable named InterestRate is
treated as an entirely different variable than one
named interestRate.
There’s no limit to the length of the variable name.
You can’t use one of JavaScript’s reserved words as a
variable name (such as let, const, var, alert, or prompt).
All programming languages have a supply of words
that are used internally by the language and that can’t
be used for variable names, because doing so would
cause confusion (or worse).
Ideas for good variable names
The process of declaring a variable doesn’t take much
thought, but that doesn’t mean you should just type in
any old variable name that comes to mind. Take a few
extra seconds to come up with a good name by following
these guidelines:
Make your names descriptive. Sure, using names
that are just a few characters long makes them easier
to type, but I guarantee you that you won’t remember
what the variables represent when you look at the
script down the road. For example, if you want a
variable to represent an account number, use
accountNumber or accountNum instead of, say, acnm or
accnum.
44. Mostly avoid single-letter names. Although
it’s best to avoid single-letter variable names, such
short names are accepted in some places, such as
when constructing loops, as described in Chapter 4.
Use multiple words with no spaces. The best way
to create a descriptive variable name is to use multiple
words. However, because JavaScript doesn’t take
kindly to spaces in names, you need some way of
separating the words to keep the name readable. The
two standard conventions for using multi-word variable
names are camelCase, where you cram the words
together and capitalize all but the first word (for
example, lastName), or to separate each word with an
underscore (for example, last_name). I prefer the former
style, so I use it throughout this book.
Use separate naming conventions. Use one
naming convention for JavaScript variables and a
different one for HTML identifiers and CSS classes. For
example, if you use camelCase for multiword
JavaScript variables, use dashes to separate words for
id values and class names.
Differentiate your variable names from
JavaScript keywords. Try to make your variable
names look as different from JavaScript’s keywords
and other built-in terms (such as alert) as possible.
Differentiating variable names helps avoid the
confusion that can arise when you look at a term and
you can’t remember if it’s a variable or a JavaScript
word.
Don’t make your names too long. Although short,
cryptic variable names are to be shunned in favor of
longer, descriptive names, that doesn’t mean you
45. should be using entire sentences. Extremely long
names are inefficient because they take so long to
type, and they’re dangerous because the longer the
name, the more likely you are to make a typo. Names
of 2 to 4 words and 8 to 20 characters should be all
you need.
Understanding Literal
Data Types
In programming, a variable’s data type specifies what
kind of data is stored within the variable. The data type
is a crucial idea because it determines not only how two
or more variables are combined (for example,
mathematically), but also whether they can be combined
at all. Literals are a special class of data type, and they
cover those values that are fixed (even if only
temporarily). For example, consider the following
variable assignment statement:
let todaysQuestion = "What color is your parachute?";
Here, the text "What color is your parachute?" is a literal
string value. JavaScript supports three kinds of literal
data types: numeric, string, and Boolean. The next three
sections discuss each type.
Working with numeric literals
Unlike many other programming languages, JavaScript
treats all numbers the same, so you don’t have to do
anything special when working with the two basic
numeric literals, which are integers and floating-point
numbers:
Integers: These are numbers that don’t have a
fractional or decimal part. So, you represent an integer
46. using a sequence of one or more digits, as in these
examples:
0
42
2001
-20
Floating-point numbers: These are numbers that do
have a fractional or decimal part. Therefore, you
represent a floating-point number by first writing the
integer part, followed by a decimal point, followed by
the fractional or decimal part, as in these examples:
0.07
3.14159
-16.6666667
7.6543e+21
1.234567E-89
Exponential notation
The last two floating-point examples require a bit more
explanation. These two use exponential notation, which
is an efficient way to represent really large or really
small floating-point numbers. Exponential notation uses
an e (or E) followed by the exponent, which is a number
preceded by a plus sign (+) or a minus sign (-).
You multiply the first part of the number (that is, the
part before the e or E) by 10 to the power of the
exponent. Here’s an example:
9.87654e+5;
The exponent is 5, and 10 to the power of 5 is 100,000.
So, multiplying 9.87654 by 100,000 results in the value
987,654.
Here’s another example:
3.4567e-4;
47. The exponent is -4, and 10 to the power of -4 is 0.0001.
So, multiplying 3.4567 by 0.0001 results in the value
.00034567.
Hexadecimal integer values
You’ll likely deal with the usual decimal (base-10)
number system throughout most of your JavaScript
career. However, just in case you have cause to work
with hexadecimal (base-16) numbers, this section shows
you how JavaScript deals with them.
The hexadecimal number system uses the digits 0
through 9 and the letters A through F (or a through f),
where these letters represent the decimal numbers 10
through 15. So, what in the decimal system would be 16
is actually 10 in hexadecimal. To specify a hexadecimal
number in JavaScript, begin the number with a 0x (or
0X), as shown in the following examples:
0x23;
0xff;
0X10ce;
Working with string literals
A string literal is a sequence of one or more letters,
numbers, or punctuation marks, enclosed either in
double quotation marks (") or single quotation marks (').
Here are some examples:
"JavaScript Essentials";
'August 23, 1959';
"";
"What's the good word?";
The string "" (or '' — two consecutive single
quotation marks) is called the null string. It
48. represents a string that doesn’t contain any
characters.
Using quotation marks within strings
The final example in the previous section shows that it’s
okay to insert one or more instances of one of the
quotation marks (such as ') inside a string that’s
enclosed by the other quotation mark (such as "). Being
able to nest quotation marks comes in handy when you
need to embed one string inside another, which is very
common (particularly when using bits of JavaScript
within HTML tags). Here’s an example:
onsubmit="processForm('testing')";
However, it’s illegal to insert in a string one or more
instances of the same quotation mark that encloses the
string, as in this example:
"This is "illegal" in JavaScript.";
Understanding escape sequences
What if you must include, say, a double quotation mark
within a string that’s enclosed by double quotation
marks? Having to nest the same type of quotation mark
is rare, but it is possible if you precede the double
quotation mark with a backslash (), like this:
"The double quotation mark (") encloses this string.";
The " combination is called an escape sequence. You
can combine the backslash with a number of other
characters to form other escape sequences, and each one
enables the browser to represent a character that, by
itself, would be illegal or not representable otherwise.
Table 2-1 lists the most commonly used escape
sequences.
49. TABLE 2-1 Common JavaScript Escape
Sequences
Escape Sequence Character It Represents
' Single quotation mark
" Double quotation mark
b Backspace
f Form feed
n New line
r Carriage return
t Tab
Backslash
The following code shows an example script that uses the
n escape sequence to display text on multiple lines with
an alert box.
alert("This is line 1.nSo what. This is line 2.");
Figure 2-4 shows the result.
FIGURE 2-4: Using the n escape sequence enables you to format text so that it
displays on different lines.
50. To learn how to combine two or more string literals,
check out Chapter 3. Also, JavaScript has a nice
collection of string manipulation features, which I
discuss in Chapter 8.
Working with Boolean literals
Booleans are the simplest of all the literal data types
because they can assume only one of two values: true or
false. That simplicity may make it seem as though
Booleans aren’t particularly useful, but the capability to
test whether a particular variable or condition is true or
false is invaluable in JavaScript programming.
You can assign Boolean literals directly to a variable, like
this:
taskCompleted = true;
Alternatively, you can work with Boolean values
implicitly using expressions:
currentMonth === "August"
The comparison expression currentMonth === "August" asks
the following: Does the value of the currentMonth variable
equal the string "August"? If it does, the expression
evaluates to the Boolean value true; if it doesn’t, the
expression evaluates to false. I discuss much more about
comparison expressions in Chapter 3.
51. Chapter 3
Building Expressions
IN THIS CHAPTER
Understanding what expressions are
Figuring out numeric expressions
Tying up string expressions
Getting the hang of comparison expressions
Learning about logical expressions
When coding in JavaScript, you use expressions
constantly, so it’s vital to understand what they are and
to get comfortable with the types of expressions that are
available to you. Every JavaScript coder is different, but I
can say without fear of contradiction that every good
JavaScript coder is fluent in expressions.
This chapter takes you through everything you need to
know about expressions. You discover some expression
basics and then explore a number of techniques for
building powerful expressions using numbers, strings,
and Boolean values.
Understanding How
Expressions Are
Structured
A JavaScript expression takes one or more inputs, such
as a bill total and a tip percentage, and combines them in
52. some way — for example, by using multiplication. In
expression lingo, the inputs are called operands, and
they’re combined by using special symbols called
operators.
operand: An input value for an expression. It is, in
other words, the raw data that the expression
manipulates to produce its result. It could be a
number, a string, a variable, a function result (refer to
Chapter 5), or an object property (refer to Chapter 6).
operator: A symbol that represents a particular action
performed on one or more operands. For example, the
* operator represents multiplication, and the + operator
represents addition. I discuss the various JavaScript
operators throughout this chapter.
For example, here’s an expression that calculates a tip
amount and assigns the result to a variable:
tipAmount = billTotal * tipPercentage;
The expression is everything to the right of the equals
sign (=). Here, billTotal and tipPercentage are the
operands, and the multiplication sign (*) is the operator.
Creating Numeric
Expressions
In JavaScript, a mathematical calculation is called a
numeric expression, and it combines numeric operands
and arithmetic operators to produce a numeric result.
This section discusses all the JavaScript arithmetic
operators and shows you how best to use them to build
useful and handy numeric expressions.
53. Table 3-1 lists the basic arithmetic operators you can use
in your JavaScript expressions.
JavaScript also comes with a few extra operators that
combine some of the arithmetic operators and the
assignment operator, which is the humble equals sign (=)
that assigns a value to a variable. Table 3-2 lists these so-
called arithmetic assignment operators.
TABLE 3-1 The JavaScript Arithmetic
Operators
Operator Name Example Result
+ Addition 10 + 4 14
++ Increment 10++ 11
- Subtraction 10 - 4 6
- Negation -10 -10
-- Decrement 10-- 9
* Multiplication 10 * 4 40
/ Division 10 / 4 2.5
% Modulus 10 % 4 2
TABLE 3-2 The JavaScript Arithmetic
Assignment Operators
Operator Example Equivalent
+= x += y x = x + y
-= x -= y x = x - y
*= x *= y x = x * y
/= x /= y x = x / y
^= x ^= y x = x ^ y
%= x %= y x = x % y
54. Building String
Expressions
A string expression is one where at least one of the
operands is a string, and the result of the expression is
another string. String expressions are straightforward in
the sense that there is only one operator to deal with:
concatenation (+). You use this operator to combine (or
concatenate) strings within an expression. For example,
the expression "Java" + "Script" returns the string
"JavaScript". Note, however, that you can also use strings
with the comparison operators discussed in the next
section.
Building Comparison
Expressions
You use comparison expressions to compare the values
of two or more numbers, strings, variables, properties, or
function results. If the expression is true, the expression
result is set to the Boolean value true; if the expression is
false, the expression result is set to the Boolean value
false. You’ll use comparisons with alarming frequency in
your JavaScript code, so it’s important to understand
what they are and how you use them.
Table 3-3 summarizes JavaScript’s comparison operators.
TABLE 3-3 The JavaScript Comparison
Operators
Operator Name Example Result
== Equality 10 == 4 false
56. The Dean grew more earnest. Other pamphlets followed: for
instance, in 1775, “An Humble Address and Earnest Appeal, …
whether a Connection with or a Separation from the Continental
Colonies of America be most for the National Advantage and the
Lasting Benefit of these Kingdoms.” Here he says openly:—
“My scheme, which Mr. Burke, in his last speech, of
March 22, 1775, is pleased to term a childish one, is,
To separate totally from the Colonies, and to reject
them from being fellow-members and joint partakers
with us in the privileges and advantages of the British
Empire, because they refuse to submit to the authority
and jurisdiction of the British legislature,—offering at
the same time to enter into alliances of friendship and
treaties of commerce with them, as with any other
sovereign, independent state.”[453]
Then, insisting that his scheme “most infallibly cuts off all the
present causes of dispute and contention between the two
countries, so that they never can revive again,”[454]
he establishes
that commercial intercourse with the Americans would not cease,
inasmuch as it cannot be shown that they “will no longer adhere to
their own interest when they shall be disunited from us.”[455]
Among subsequent tracts was one entitled “Cui Bono? or, An
Inquiry, What Benefits can arise either to the English or the
Americans, the French, Spaniards, or Dutch, from the Greatest
Victories or Successes in the Present War? Being a Series of Letters
addressed to Monsieur Necker, late Controller-General of the
Finances of France. London, 1782.” Here was the same ardor for
separation, with the same bitter words for the Colonies.
Tardily the foresight of the Dean was recognized, until at last
Archbishop Whately, in his annotations upon Bacon’s Essay on Honor
and Reputation, commemorates it as an historic example. According
to him, “the whole British nation were in one particular manifestly
puzzle-headed, except one man, who was accordingly derided by
57. all.” Then mentioning the dispute between the mother country and
her colonies, he says: “But Dean Tucker, standing quite alone, wrote
a pamphlet to show that the separation would be no loss at all, and
that we had best give them the independence they coveted at once
and in a friendly way. Some thought he was writing in jest; the rest
despised him, as too absurd to be worth answering. But now, and
for above half a century, every one admits that he was quite right,
and regrets that his view was not adopted.”[456]
Unquestionably this
is a remarkable tribute. Kindred to it was that of the excellent
Professor Smyth, who, in exhibiting the “American War,” dwells on
“the superior and the memorable wisdom of Tucker.”[457]
The bad temper shooting from his writings interfered, doubtless,
with their acceptance. His spirit, so hostile to us, justified his own
characterization of himself as “the author of these tracts against the
rebel Americans.” As the war drew to a close, his bad temper still
prevailed, heightened by antipathy to republicanism, so that, after
picturing the Colonies, separated at last from the mother country, as
having “gained a general disappointment mixed with anger and
indignation,”[458]
he thus predicts their terrible destiny:—
“As to the future grandeur of America, and its being
a rising empire under one head, whether republican or
monarchical, it is one of the idlest and most visionary
notions that ever was conceived, even by writers of
romance. For there is nothing in the genius of the
people, the situation of their country, or the nature of
their different climates, which tends to countenance
such a supposition.… Above all, when those immense
inland regions beyond the back settlements, which are
still unexplored, are taken into the account, they form
the highest probability that the Americans never can
be united into one compact empire, under any species
of government whatever. Their fate seems to be—a
disunited people till the end of time.”[459]
58. Alas! But evidently the Dean saw the future of our continent no
better than the Ministry saw their duty with regard to it.
Unlike in spirit was Matthew Robinson, a contemporary friend of
America, whose able and elaborate tracts[460]
in successive editions
are now forgotten, except so far as revived by the notice of
Professor Smyth.[461]
His vindication of the Colonies, at the time of
the Boston Port Bill, was complete, without the harshness of Tucker,
and he did not hesitate to present the impossibility of conquering
them. “What expectation or probability,” he asks, “can there be of
sending from hence armies capable to conquer and subdue so great
a force of men defending and defended by such a continent?”[462]
Then, while depicting English mastery of the sea, he says: “We may
do whatever a fleet can. Very true; but it cannot sail all over North
America.”[463]
The productions of this enlightened author cannot have
been without effect. Doubtless they helped the final
acknowledgment of independence. When will the “Old Mortality”
appear, to discover and restore his monument?
The able annotator of Lord Bacon was too sweeping, when he said
that on the great American question all England was wrong, “except
one man.” Robinson was as right as the Dean, and there were others
also. The “Monthly Review,” in an article on the Dean’s appeal for
separation, said: “This, however, is not a new idea. It has frequently
occurred to others.”[464]
Even Soame Jenyns, a life-long member of
Parliament, essayist, poet, defender of Christianity, while upholding
the right to tax the Colonies, is said to have accepted the idea of
“total separation”:—
“Let all who view th’ instructive scene,
And patronize the plan,
Give thanks to Gloucester’s honest Dean,
For, Tucker, thou’rt the man.”[465]
59. In a better spirit, and with affecting earnestness, John Cartwright,
once of the Royal Navy, and known as Major from his rank in the
Nottinghamshire Militia, followed the Dean, in 1774, with a series of
letters collected in a pamphlet entitled “American Independence the
Interest and Glory of Great Britain,” where he insists upon
separation, and thenceforward a friendly league, “that the true and
lasting welfare of both countries can be promoted.”[466]
In enforcing
his conclusion the author says: “When we talk of asserting our
sovereignty over the Americans, do we foresee to what fatal lengths
it will carry us? Are not those nations increasing with astonishing
rapidity? Must they not, in the nature of things, cover in a few ages
that immense continent like a swarm of bees?”[467]
Then again: “We
may, indeed, by means of fleets and armies, maintain a precarious
tyranny over the Americans for a while; but the most shallow
politicians must foresee what this would end in.”[468]
Then, in reply to
the Dean: “’Tis a pity so able a writer had not discovered that the
Americans have a right to choose their own governors, and thence
enforced the necessity of his proposed separation as a religious duty,
no less than a measure of national policy.”[469]
Cartwright continued
at home the conflicts of principle involved in our War of
Independence, and became an English Reformer. Honor to his name!
DAVID HARTLEY, 1775, 1776, 1777, 1785.
Another English friend was David Hartley. He was constant and
even pertinacious on our side, although less prophetic than Pownall,
with whom he coöperated in purpose and activity. His father was
Hartley the metaphysician, and author of the ingenious theory of
sensation, who predicted the fate of existing governments and
hierarchies in two simple sentences: “It is probable that all the
present Civil Governments will be overturned”; “It is probable that
the present forms of Church Government will be dissolved.”[470]
Many
were alarmed. Lady Charlotte Wentworth asked the prophet when
these terrible things would happen. The answer was: “I am an old
60. man, and shall not live to see them; but you are a young woman,
and probably will see them.”[471]
The son was born in 1729, and died at Bath in 1813. During our
Revolution he sat in Parliament for Kingston-upon-Hull. He was also
the British plenipotentiary in negotiating the Definitive Treaty of
Peace with the United States. He has dropped out of sight. The
biographical dictionaries afford him a few lines only. But he deserves
a considerable place in the history of our Independence.
John Adams was often austere, and sometimes cynical, in his
judgments. Evidently he did not like Hartley. In one place he speaks
of him as “a person of consummate vanity”;[472]
then, as “talkative
and disputatious, and not always intelligible”;[473]
and in still another
place remarks, “Mr. Hartley was as copious as usual;”[474]
and when
appointed to sign the Definitive Treaty, “It would have been more
agreeable to have finished with Mr. Oswald.”[475]
And yet, when
writing most elaborately to the Comte de Vergennes on the state of
affairs previous to the final campaign, he introduces opinions of
Hartley at length, saying that he was “more for peace than any man
in the kingdom.”[476]
Such testimony may well outweigh the other
expressions, especially as nothing of the kind appears in the
correspondence of Franklin, with whom Hartley was much more
intimate.
The “Parliamentary History” is a sufficient monument for Hartley.
He was a frequent speaker, and never missed an opportunity of
pleading our cause. Although without the immortal eloquence of
Burke, he was always clear and full. Many of his speeches seem
written out by himself. He was not a tardy convert, but began as “a
new member” by supporting an amendment favorable to the
Colonies, 5th December, 1774. Then, in March, 1775, he brought
forward “Propositions for Conciliation with America,” which he
sustained in an elaborate speech, where he avowed that the
American question had occupied him for some time:—
61. “Though I have so lately had the honor of a seat in
this House, yet I have for many years turned my
thoughts and attention to matters of public concern
and national policy. This question of America is now of
many years’ standing.”[477]
In this speech he acknowledges the services of New England at
Louisburg:—
“In that war too, Sir, they took Louisburg from the
French, single-handed, without any European
assistance: as mettled an enterprise as any in our
history; an everlasting memorial of the zeal, courage,
and perseverance of the troops of New England. The
men themselves dragged the cannon over a morass
which had always been thought impassable, where
neither horses nor oxen could go; and they carried the
shot upon their backs. And what was their reward for
this forward and spirited enterprise,—for the reduction
of this American Dunkirk? Their reward, Sir, you know
very well: it was given up for a barrier to the
Dutch.”[478]
All his various propositions were negatived; but he was not
disheartened. Constantly he spoke,—now on the Budget, then on
the Address, and then on specific propositions. At this time he
asserted the power of Parliament over the Colonies, and he
proposed, on the 2d November, 1775, that a test of submission by
the Colonists should be the recognition of an Act of Parliament
enacting “that all the slaves in America should have the trial by
jury.”[479]
Shortly afterwards, on the 7th December, 1775, he brought
forward a second set of “Propositions for Conciliation with America,”
where, among other things, he embodied the test on slavery, which
he put forward as a compromise; and here his language belongs not
only to the history of our Revolution, but to the history of
Antislavery. While declaring that in his opinion Great Britain was “the
62. aggressor in everything,”[480]
he sought to bring the two countries
together on a platform of human rights, which he thus explained:—
“The act to be proposed to America, as an
auspicious beginning to lay the first stone of universal
liberty to mankind, should be what no American could
hesitate an instant to comply with, namely, that every
slave in North America should be entitled to his trial by
jury in all criminal cases. America cannot refuse to
accept and to enroll such an act as this, and thereby to
reëstablish peace and harmony with the parent state.
Let us all be reunited in this, as a foundation to
extirpate slavery from the face of the earth. Let those
who seek justice and liberty for themselves give that
justice and liberty to their fellow-creatures. With
respect to the idea of putting a final period to slavery
in North America, it should seem best that when this
country had led the way by the act for jury, that each
Colony, knowing their own peculiar circumstances,
should undertake the work in the most practicable
way, and that they should endeavor to establish some
system by which slavery should be in a certain term of
years abolished. Let the only contention henceforward
between Great Britain and America be, which shall
exceed the other in zeal for establishing the
fundamental rights of liberty to all mankind.”[481]
How grand and beautiful!—not to be read without gratitude! The
motion was rejected; but among the twenty-three in its favor were
Fox and Burke.
During this same month the unwearied defender of our country
came forward again, declaring that he could not be “an adviser or a
well-wisher to any of the vindictive operations against America,
because he thought the cause unjust; but at the same time he must
be equally earnest to secure British interests from destruction”; and
he thus prophesies:—
63. “The fate of America is cast. You may bruise its heel,
but you cannot crush its head. It will revive again. The
New World is before them. Liberty is theirs. They have
possession of a free government, their birthright and
inheritance, derived to them from their parent state,
which the hand of violence cannot wrest from them. If
you will cast them off, my last wish is to them, May
they go and prosper!”[482]
Again, on the 10th May, 1776, he vindicated anew his original
proposition; and here again he testifies for peace and against
slavery:—
“For the sake of peace, therefore, I did propose a
test of compromise, by an acceptance, on the part of
the Colonists, of an Act of Parliament which should lay
the foundation for the extirpation of the horrid custom
of slavery in the New World.… My motion was …
simply as an act of compromise and reconciliation;
and, as far as it was a legislative act, it was still to
have been applied in correcting the laws of slavery in
America, which I considered as repugnant to the laws
of the realm of England, and to the fundamentals of
our Constitution. Such a compromise would at the
same time have saved the national honor.”[483]
All gratitude to the hero who at this early day vowed himself to
the abolition of slavery! Hartley is among the first of Abolitionists,
with hardly a predecessor except Granville Sharp, and in Parliament
absolutely the first. Clarkson was at this time fifteen years old,
Wilberforce sixteen. Only in 1785 Clarkson obtained the prize for the
best Latin essay on the question, “Is it right to make men slaves
against their will?”[484]
It was not until 1791 that Wilberforce moved
for leave to bring in a bill for the abolition of the slave-trade. It is no
small honor for one man to have come forward in Parliament as an
avowed abolitionist, while at the same time a vindicator of our
independence.
64. Again, on the 15th May, 1777, Hartley pleaded for us:—
“At sea, which has hitherto been our prerogative
element, they rise against us at a stupendous rate;
and if we cannot return to our old mutual hospitalities
towards each other, a very few years will show us a
most formidable hostile marine, ready to join hands
with any of our enemies.… I will venture to prophesy
that the principles of a federal alliance are the only
terms of peace that ever will and that ever ought to
obtain between the two countries.”[485]
On the 5th of June, three weeks afterwards, the “Parliamentary
History” reports briefly:—
“Mr. Hartley went upon the cruelties of slavery, and
urged the Board of Trade to take some means of
mitigating it. He produced a pair of handcuffs, which
he said was a manufacture they were now going to
establish.”[486]
Thus again the abolitionist reappeared in the vindicator of our
independence. On the 22d June, 1779, he brought forward another
formal motion “for reconciliation with America,” and, in the course of
a well-considered speech, denounced the ministers for “headstrong
and inflexible obstinacy in prosecuting a cruel and destructive
American war.”[487]
On the 3d December, 1779, in what is called “a
very long speech,” he returned to his theme, inveighing against
ministers for “the favorite, though wild, Quixote, and impracticable
measure of coercing America.”[488]
These are only instances.
During this time he maintained relations with Franklin, as appears
in the “Diplomatic Correspondence of the Revolution,” all of which
attests a desire for peace. In 1778 he arrived at Paris on a
confidential errand, especially to confer with Franklin. On this
occasion John Adams met him and judged him severely. In 1783 he
was appointed a commissioner to sign the Definitive Treaty of Peace.
65. These things belong to history. Though perhaps not generally
known, they are accessible. I have presented them for their intrinsic
value and prophetic character, but also as the introduction to an
unpublished letter from Hartley, which I received some time ago
from an English friend, who has since been called away from
important labors. The letter concerns emigration to our country, and
the payment of the national debt. The following indorsement
explains its character:—
“Note. This is a copy of the material portion of a long
letter from D. Hartley, the British Commissioner in
Paris, to Lord Sydenham, January, 1785. The original
was sold by C. Robinson, of 21 Bond Street, London,
on the 6th April, 1859, at a sale of Hartley’s MSS. and
papers, chiefly relating to the United States of
America. It was Hartley’s copy, in his own hand.
“The lot was No. 82 in the sale catalogue. It was
bought by J. R. Smith, the London bookseller, for £2
6s. 0d.
“I had a copy made before the sale.
“Joseph Parkes.
“London, 18 July, ’59.”
The letter is as follows:—
“My Lord,—In your Lordship’s last letter to me, just
before my leaving Paris, you are pleased to say that
any information which I might have been able to
collect of a nature to promote the mutual and
reciprocal interests of Great Britain and the United
States of America would be extremely acceptable to
his Majesty’s government.… Annexed to this letter I
have the honor of transmitting to your Lordship some
66. papers and documents which I have received from the
American ministers. One of them (No. 5) is a Map of
the Continent of North America, in which the land
ceded to them by the late treaty of peace is divided by
parallels of latitude and longitude into fourteen new
States.
“The whole project, in its full extent, would take
many years in its execution, and therefore it must be
far beyond the present race of men to say, ‘This shall
be so.’ Nevertheless, those who have the first care of
this New World will probably give it such directions and
inherent influences as may guide and control its course
and revolutions for ages to come. But these plans,
being beyond the reach of man to predestinate, are
likewise beyond the reach of comment or speculation
to say what may or may not be possible, or to predict
what events may hereafter be produced by time,
climates, soils, adjoining nations, or by the unwieldy
magnitude of empire, and the future population of
millions superadded to millions. The sources of the
Mississippi may be unknown; the lines of longitude and
latitude may be extended into unexplored regions; and
the plan of this new creation may be sketched out by a
presumptuous compass, if all its intermediate uses and
functions were to be suspended until the final and
precise accomplishment, without failure or deviation,
of this unbounded plan. But this is not the case; the
immediate objects in view are limited and precise; they
are of prudent thought, and within the scope of human
power to measure out and to execute. The principle,
indeed, is indefinite, and will be left to the test of
future ages to determine its duration or extent.
“I take the liberty to suggest thus much, lest we
should be led away to suppose that the councils which
67. have produced these plans have had no wiser or more
sedate views than merely the amusement of drawing
meridians of ambition and high thoughts. There
appear to me to be two solid and rational objects in
view: the first is, by the sale of lands nearly contiguous
to the present States, (receiving Congress paper in
payment according to its scale of depreciation,) to
extinguish the present national debt, which I
understand might be discharged for about twelve
millions sterling.…
“It is a new proposition to be offered to the
numerous common rank of mankind in all the countries
of the world, to say that there are in America fertile
soils and temperate climates in which an acre of land
may be purchased for a trifling consideration, which
may be possessed in freedom, together with all the
natural and civil rights of mankind. The Congress have
already proclaimed this, and that no other qualification
or name is necessary but to become settlers, without
distinction of countries or persons. The European
peasant, who toils for his scanty sustenance in penury,
wretchedness, and servitude, will eagerly fly to this
asylum for free and industrious labor. The tide of
emigration may set strongly outward from Scotland,
Ireland, and Canada to this new land of promise.
“A very great proportion of men in all the countries
of the world are without property, and generally are
subject to governments of which they have no
participation, and over whom they have no control.
The Congress have now opened to all the world a sale
of landed settlements where the liberty and property
of each individual is to be consigned to his own
custody and defence.… These are such propositions of
free establishments as have never yet been offered to
68. mankind, and cannot fail of producing great effects in
the future progress of things. The Congress have
arranged their offers in the most inviting and artful
terms; and lest individual peasants and laborers should
not have the means of removing themselves, they
throw out inducements to moneyed adventurers to
purchase and to undertake the settlement by
commission and agency, without personal residence,
by stipulating that the lands of proprietors being
absentees shall not be higher taxed than the lands of
residents. This will quicken the sale of lands, which is
their object.
“For the explanation of these points, I beg leave to
refer your Lordship to the documents annexed, Nos. 5
and 6,—namely, the Map, and Resolutions of Congress,
dated April, 1784. Another circumstance would confirm
that it is the intention of Congress to invite moneyed
adventurers to make purchases and settlements, which
is the precise and mathematical mode of dividing and
marking out for sale the lands in each new proposed
State. These new States are to be divided by parallel
lines running north and south, and by other parallels
running east and west. They are to be divided into
hundreds of ten geographical miles square, and then
again into lots of one square mile. The divisions are
laid out as regularly as the squares upon a chessboard,
and all to be formed into a Charter of Compact.
“They may be purchased by purchasers at any
distance, and the titles may be verified by registers of
such or such numbers, north or south, east or west: all
this is explained by the document annexed, No. 7,
namely, The Ordinance for ascertaining the mode of
locating and disposing of lands in the Western
Territory. This is their plan and means for paying off
69. their national debt, and they seem very intent upon
doing it. I should observe that their debt consists of
two parts, namely, domestic and foreign. The sale of
lands is to be appropriated to the former.
“The domestic debt may perhaps be nine or ten
millions, and the foreign debt two or three. For
payment of the foreign debt it is proposed to lay a tax
of five per cent. upon all imports until discharged,
which, I am informed, has already been agreed to by
most of the States, and probably will soon be
confirmed by the rest. Upon the whole, it appears that
this plan is as prudently conceived and as judiciously
arranged, as to the end proposed, as any experienced
cabinet of European ministers could have devised or
planned any similar project.
“The second point which appears to me to be
deserving of attention, respecting the immense cession
of territory to the United States at the late peace, is a
point which will perhaps in a few years become an
unparalleled phenomenon in the political world. As
soon as the national debt of the United States shall be
discharged by the sale of one portion of those lands,
we shall then see the Confederate Republic in a new
character, as a proprietor of lands either for sale or to
let upon rents. While other nations may be struggling
under debts too enormous to be discharged either by
economy or taxation, and while they may be laboring
to raise ordinary and necessary supplies by
burdensome impositions upon their own persons and
properties, here will be a nation possessed of a new
and unheard-of financial organ of stupendous
magnitude, and in process of time of unmeasured
value, thrown into their lap as a fortuitous superfluity,
and almost without being sought for.
70. “When such an organ of revenue begins to arise into
produce and exertion, what public uses it may be
applicable to, or to what abuses and perversions it
might be rendered subservient, is far beyond the reach
of probable discussion now. Such discussions would
only be visionary speculations. However, thus far it is
obvious, and highly deserving of our attention, that it
cannot fail becoming to the American States a most
important instrument of national power, the progress
and operation of which must hereafter be a most
interesting object of attention to the British American
dominions which are in close vicinity to the territories
of the United States; and I should hope that these
considerations would lead us, inasmuch as we value
those parts of our dominions, to encourage conciliatory
and amicable correspondence between them and their
neighbors.”
This private communication, now for the first time seeing the light,
is full of prophecy, or of that remarkable discernment and forecast
which mark the prophetic spirit, whether in announcing “the future
population of millions superadded to millions,” or in the high
estimate of the National Territory, destined to become in a few years
“an unparalleled phenomenon in the political world,” “a new and
unheard-of financial organ of stupendous magnitude.” How few at
home saw the Public Lands with as clear a vision as Hartley!
GALIANI, 1776, 1778.
Among the most brilliant in this extending list is the Abbé Galiani,
the Neapolitan, who was born 1728, and died at Naples 1787.
Although Italian by birth, yet by the accident of official residence he
became for a while domesticated in France, wrote the French
language, and now enjoys a French reputation. His writings in
French and his letters have the wit and ease of Voltaire.
71. Galiani was a genius. Whatever he touched shone at once with his
brightness, in which there was originality as well as knowledge. He
was a finished scholar, and very successful in lapidary verses. Early
in life, while in Italy, he wrote a grave essay on Money, which
contrasted with another of rare humor suggested by the death of
the public executioner. Other essays followed; and then came the
favor of the congenial pontiff, Benedict the Fourteenth. In 1760 he
found himself at Paris as Secretary of the Neapolitan Embassy.
Mingling with courtiers officially, according to the duties of his
position, he fraternized with the liberal and adventurous spirits who
exercised such influence over society and literature. He was
recognized as one of them, and inferior to none. His petty stature
was forgotten when he conversed with inexhaustible faculties of all
kinds, so that he seemed an Encyclopædia, Harlequin, and
Machiavelli all in one. The atheists at the Thursday dinner of
D’Holbach were confounded while he enforced the existence of God.
Into the questions of political economy occupying attention at the
time he entered with a pen which seemed borrowed from the French
Academy. His “Dialogues sur le Commerce des Blés” had the success
of a romance: ladies carried this book on Corn in their work-baskets.
Returning to Naples, he continued to live in Paris through his
correspondence, especially with Madame d’Épinay, the Baron
d’Holbach, Diderot, and Grimm.[489]
Among later works, after his return to Naples, was a solid volume
—not to be forgotten in the History of International Law—on the
Duties of Neutrals, where a difficult subject is treated with such
mastery, that, more than half a century later, D’Hautefeuille, in his
elaborate treatise, copies from it at length. Galiani was the
predecessor of this French writer in the extreme assertion of neutral
rights. Other works were left at his death in manuscript, some grave
and some humorous; also letters without number. The letters
preserved from Italian savans filled eight large volumes; those from
savans, ministers, and sovereigns abroad filled fourteen. His Parisian
correspondence did not see the light till 1818, although some of the
letters may be found in the contemporary correspondence of Grimm.
72. In his Parisian letters, which are addressed chiefly to that clever
individuality, Madame d’Épinay, the Neapolitan abbé shows not only
the brilliancy and nimbleness of his talent, but the universality of his
knowledge and the boldness of his speculations. Here are a few
words from a letter dated at Naples, 12th October, 1776, in which he
brings forward the idea of “races,” so important in our day, with an
illustration from Russia:—
“All depends upon races. The first, the most noble of
races, comes naturally from the North of Asia. The
Russians are the nearest to it, and this is the reason
why they have made more progress in fifty years than
can be got out of the Portuguese in five hundred.”[490]
Belonging to the Latin race, Galiani was entitled to speak thus
freely.
In another letter to Madame d’Épinay, dated at Naples, 18th May,
1776, he had already foretold the success of our Revolution. Few
prophets have been more explicit than he was in the following
passage:—
“Livy said of his age, which so strongly resembled
ours, ‘Ad hæc tempora ventum est, quibus nec vitia
nostra nec remedia pati possumus,’—‘We are in an age
when the remedies hurt at least as much as the
vices.’[491]
Do you know how matters stand? The epoch
has come of the total downfall of Europe, and of
transmigration to America. Everything here is falling
into rottenness,—religion, laws, arts, sciences,—and
everything is going to be rebuilt anew in America. This
is no joke; nor is it an idea drawn from the English
quarrels; I have said, announced, preached it, for
more than twenty years, and I have always seen my
prophecies fulfilled. Do not buy your house, then, in
the Chaussée d’Antin; you must buy it in Philadelphia.
My trouble is, that there are no abbeys in America.”[492]
73. This letter was written some months before the Declaration of
Independence.
In another, dated at Naples, 7th February, 1778, the Abbé alludes
to the great numbers of English men and women who have come to
Naples “for shelter from the American tempests,” and adds,
“Meanwhile the Washingtons and Hancocks will be fatal to them.”[493]
In still another, dated at Naples, 25th July, 1778, he renews his
prophecies in language still more explicit:—
“You will at this time have decided the greatest
revolution of the globe,—namely, if it is America which
is to reign over Europe, or if it is Europe which is to
continue to reign over America. I would wager in favor
of America, for the reason, merely physical, that for
five thousand years genius has turned opposite to the
diurnal motion, and travelled from East to West.”[494]
Here again is the idea of Berkeley which has been so captivating.
ADAM SMITH, 1776.
In contrast with the witty Italian is the illustrious philosopher and
writer of Scotland, Adam Smith, who was born 5th June, 1723, and
died 17th July, 1790. His fame is so commanding that any details of
life or works would be out of place. He was thinker and inventor,
through whom mankind was advanced in knowledge.
I say nothing of his “Theory of Moral Sentiments,” constituting an
important contribution to the science of Ethics, but come at once to
his great work of political economy, entitled “An Inquiry into the
Nature and Causes of the Wealth of Nations,” which first appeared in
1776. Its publication marks an epoch described by Mr. Buckle, when
he says that Adam Smith, “by the publication of this single work,
contributed more towards the happiness of man than has been
effected by the united abilities of all the statesmen and legislators of
whom history has preserved an authentic account.”[495]
The work is
74. full of prophetic knowledge, and especially with regard to the British
Colonies. Writing while the debate with the mother country was still
pending, Adam Smith urged that they should be admitted to
Parliamentary representation in proportion to taxation, so that their
representation would enlarge with their growing resources; and here
he predicts nothing less than the transfer of empire:—
“The distance of America from the seat of
government, the natives of that country might flatter
themselves, with some appearance of reason too,
would not be of very long continuance. Such has
hitherto been the rapid progress of that country in
wealth, population, and improvement, that, in the
course of little more than a century, perhaps, the
produce of American might exceed that of British
taxation. The seat of the empire would then naturally
remove itself to that part of the empire which
contributed most to the general defence and support
of the whole.”[496]
In these tranquil words of assured science the great author carries
the seat of government across the Atlantic.
Did Adam Smith in this remarkable passage do more than follow a
hint from our own prophet? The prophecy of the great economist
first appeared in 1776. In the course of 1774, and down to April 19,
1775, John Adams published in the “Boston Gazette” a series of
weekly articles, under the signature of “Novanglus,” which were
abridged in Almon’s “Remembrancer” for 1775, with the following
title: “History of the Dispute with America, from its Origin in 1754 to
the Present Time.” Although this abridged edition stops before the
prophetic passage, it is not impossible that the whole series was
known to Adam Smith. After speculating, as the latter did
afterwards, on the extension of the British Constitution and
Parliamentary representation to the outlying British dominions, our
prophet says:—
75. “If in twenty years more America should have six
millions of inhabitants, as there is a boundless territory
to fill up, she must have five hundred representatives.
Upon these principles, if in forty years she should have
twelve millions, a thousand; and if the inhabitants of
the three kingdoms remain as they are, being already
full of inhabitants, what will become of your supreme
legislative? It will be translated, crown and all, to
America. This is a sublime system for America. It will
flatter those ideas of independency which the Tories
impute to them, if they have any such, more than any
other plan of independency that I have ever heard
projected.”[497]
Thus plainly was John Adams precursor of Adam Smith.
In 1784 these papers were reprinted from the “Remembrancer,” by
Stockdale, in London, bearing the same title, substantially, as before,
“History of the Dispute with America, from its Origin in 1754,” with
the addition, “Written in the Year 1774, by John Adams, Esq.” The
“Monthly Review,” in a notice of the publication, after speaking of
“the inauspicious system of American taxation,” says, “Mr. Adams
foretold the consequence of obstinately adhering to it, and the event
hath too well verified his predictions. They were, however,
predictions which required no inspiration.”[498]
So that his wise
second-sight was recognized in England much beyond the prevision
of Adam Smith.
The idea of transferring the seat of government to America was
often attributed to Franklin by Dean Tucker. The former, in a letter,
as early as 25th November, 1767, reports the Dean as saying, “That
is his constant plan.”[499]
In one of his tracts, the Dean attributes it
not only to Franklin, but also to our people. With strange
exaggeration he says: “It has been the unanimous opinion of the
North Americans for these fifty years past, that the seat of empire
ought to be transferred from the lesser to the greater country,—that
is, from England to America, or, as Dr. Franklin elegantly phrased it,
76. from the cock-boat to the man-of-war.”[500]
It is impossible to say
how much of this was from the excited brain of the Dean.
RICHARD PRICE, 1776, 1777, 1778, 1784.
A true and solid ally of our country at a critical period was Dr.
Price, dissenting clergyman, metaphysician, political writer, and
mathematician, who was born in Wales, 23d February, 1723, and
died in London, 19th April, 1791.
His earliest labors were “A Review of the Principal Questions and
Difficulties in Morals,” by which he was recognized as a
metaphysician, and “Observations on Reversionary Payments,” by
which he was recognized as an authority on a large class of financial
questions. At the same time his sermons were regarded as excellent.
Amidst these various labors he was moved to enlist as a
pamphleteer in defence of the American Colonies. This service,
prompted by a generous devotion to just principles, awakened
grateful sentiments on both sides of the ocean.
The Aldermen and Common Council of London marked their
sympathy by voting him the freedom of the city in a gold box of fifty
pounds value. The American Congress sent him a different
testimonial, officially communicated to him, being a solemn
resolution declaring “the desire of Congress to consider him a citizen
of the United States, and to receive his assistance in regulating their
finances.”[501]
In reply, under date of 18th January, 1779, while
declining the invitation, he offered “assurances that Dr. Price feels
the warmest gratitude for the notice taken of him, and that he looks
to the American States as now the hope and likely soon to become
the refuge of mankind.”[502]
Franklin and Adams contracted with him
relations of friendship. The former, under date of 6th February, 1780,
wrote him: “Your writings, after all the abuse you and they have met
with, begin to make serious impressions on those who at first
rejected the counsels you gave”;[503]
and 24th October, 1788, he
wrote to another: “Remember me affectionately to good Dr.
77. Price.”[504]
The latter, in correspondence many years afterwards,
recorded the intimacy he enjoyed with Dr. Price, “at his own house,
at my house, and at the houses and tables of many friends.”[505]
The first of his American tracts was in 1776, being “Observations
on the Nature of Civil Liberty, the Principles of Government, and the
Justice and Policy of the War with America.” The sale of sixty
thousand copies in a few months shows the extensive acceptance of
the work. The general principles so clearly exhibited are invoked for
America. Occasionally the philosopher becomes prophet, as when he
predicts the growth of population:—
“They are now but little short of half our number. To
this number they have grown, from a small body of
original settlers, by a very rapid increase. The
probability is that they will go on to increase, and that
in fifty or sixty years they will be double our number,
and form a mighty empire, consisting of a variety of
States, all equal or superior to ourselves in all the arts
and accomplishments which give dignity and happiness
to human life.”[506]
Nothing less than “a vast continent” seems to him the sphere of
this remarkable development, and he revolts at the idea of this being
held “at the discretion of a handful of people on the other side of the
Atlantic.”[507]
In the measures which brought on the war he saw “the
hand of Providence working to bring about some great ends.”[508]
And the vast continent was to be dedicated to Liberty. The excellent
man saw even the end of Slavery. Speaking of “the negroes of the
Southern Colonies,” he said that they “probably will now either soon
become extinct or have their condition changed into that of
freemen.”[509]
Years and battle intervened before this precious result.
This production was followed in 1777 by “Additional Observations
on the Nature and Value of Civil Liberty, and the War with
America,”—to which was added “Observations on Public Loans, the
National Debt, and the Debts and Resources of France.” In all this
78. variety of topics, his concern for America breaks forth in the inquiry,
“Must not humanity shudder at such a war?”[510]
And he sees untold
loss to England, which, with the Colonies, “might be the greatest
and happiest nation that ever existed”; but without them “we are no
more a people; … our existence depends on keeping them.”[511]
This
patriotic gloom is checked by another vision:—
“These measures have, in all probability, hastened
that disruption of the New from the Old World, which
will begin a new era in the annals of mankind, and
produce a revolution more important, perhaps, than
any that has happened in human affairs.”[512]
Thus was American Independence heralded, and its influence
foretold.
Constantly sympathizing with America, and impressed by the
magnitude of the issue, his soul found another utterance, in 1778, in
what he called “The General Introduction and Supplement to the
Two Tracts on Civil Liberty, the War with America, and the Finances
of the Kingdom.” Here again he sees a vision:—
“A great people, likely to be formed, in spite of all
our efforts, into free communities, under governments
which have no religious tests and establishments. A
new era in future annals, and a new opening in human
affairs, beginning, among the descendants of
Englishmen, in a new world. A rising empire, extended
over an immense continent, without bishops, without
nobles, and without kings.”[513]
After the recognition of Independence and the establishment of
peace, Dr. Price appeared with another tract: “Observations on the
Importance of the American Revolution and the Means of making it a
Benefit to the World.” This was in 1784. And here he repeated the
exultation of an earlier day:—
79. “With heartfelt satisfaction I see the revolution in
favor of universal liberty which has taken place in
America,—a revolution which opens a new prospect in
human affairs, and begins a new era in the history of
mankind.… Perhaps I do not go too far, when I say,
that, next to the introduction of Christianity among
mankind, the American Revolution may prove the most
important step in the progressive course of human
improvement.”[514]
Thus announcing the grandeur of the epoch, he states that it
“may produce a general diffusion of the principles of humanity,” and
may lead mankind to see and know “that all legitimate government
consists in the dominion of equal laws, made with common consent,”
which is another expression of the primal truth of the Declaration of
Independence. Then, referring to the “community or confederacy” of
States, he says, “I can almost imagine that it is not impossible but
that by such means universal peace may be produced, and all war
excluded from the world”; and he asks, “Why may we not hope to
see this begun in America?”[515]
May America be true to this
aspiration! There is also a longing for Equality, and a warning against
Slavery, with the ejaculation, in harmony with earlier words, “Let the
United States continue forever what it is now their glory to be, a
confederation of States, prosperous and happy, without lords,
without bishops, and without kings.”[516]
In the midst of the bloody
conflict this vision had appeared, and he had sought to make it a
reality.
His true friendship for our country and his devotion to humanity,
with the modesty of his nature, appear in a letter to Franklin, 12th
July, 1784, communicating a copy of the last production. After saying
that “it is intended entirely for America,” the excellent counsellor
proceeds:—
“I hope the United States will forgive my
presumption in supposing myself qualified to advise
them.… The consciousness which I have that it is well
80. intended, and that my address to them is the effusion
of a heart that wishes to serve the best interests of
society, helps to reconcile me to myself in this
instance, and it will, I hope, engage the candor of
others.”[517]
The same sentiments which proved his sympathies with our
country reappeared with fresh fires at the outbreak of the French
Revolution, arousing, in opposition, the immortal eloquence of
Burke. A discourse “On the Love of our Country,” preached at the
Old Jewry, 4th November, 1789, in commemoration of the English
Revolution, with friendly glances at what was then passing across
the Channel, prompted the “Reflections on the Revolution in France.”
The personal denunciation which is the beginning of that remarkable
performance is the perpetual witness to the position of the preacher,
whose prophetic soul did not hesitate to accept the French
Revolution side by side with ours in glory and in promise.
GOVERNOR POWNALL, 1777, 1780, 1783.
Among the best friends of our country abroad during the trials of
the Revolution was Thomas Pownall, called by one biographer “a
learned antiquary and politician,” and by another “an English
statesman and author.” Latterly he has so far dropped out of sight
that there are few who recognize in him either of these characters.
He was born 1722, and died at Bath 1805. During this long period
he held several offices. As early as 1745 he became secretary to the
Commissioners for Trade and Plantations. In 1753 he crossed the
ocean. In 1755, as Commissioner for Massachusetts Bay, he had a
share in the negotiations with New York, New Jersey, and
Pennsylvania, in union with New England, which resulted in the
confederated expedition against Crown Point. He was afterwards
Governor of Massachusetts Bay, New Jersey, and South Carolina,
successively. Returning to England, he was appointed, in 1762,
Comptroller-General of the army in Germany, with the military rank
of colonel. He sat in two successive Parliaments until 1780, when he
81. passed into private life. Hildreth gives a glimpse of his personal
character, when, admitting his frank manners and liberal politics, he
describes his habits as “rather freer than suited the New England
standard.”[518]
Pownall stands forth conspicuous for championship of our national
independence, and especially for foresight with regard to our
national future. In both these respects his writings are unique. Other
Englishmen were in favor of independence, and saw our future also;
but I doubt if any one can be named who was his equal in strenuous
action, or in minuteness of foresight. While the war was still
proceeding, as early as 1780, he openly announced, not only that
independence was inevitable, but that the new nation, “founded in
Nature and built up in truth,” would continually expand; that its
population would increase and multiply; that a civilizing activity
beyond what Europe could ever know would animate it; and that its
commercial and naval power would be found in every quarter of the
globe.[519]
All this he set forth at length with argument and
illustration, and he called his prophetic words “the stating of the
simple fact, so little understood in the Old World.” Treated at first as
“unintelligible speculation” and as “unfashionable,” the truth he
announced was “neglected where it was not rejected, but in general
rejected as inadmissible,” and the author, according to his own
language, “was called by the wise men of the British Cabinet a Wild
Man, unfit to be employed.”[520]
But these writings are a better title
now than any office. In manner they are diffuse and pedantic; but
they hardly deserve the cold judgment of John Adams, who in his
old age said of them that “a reader who has patience to search for
good sense in an uncouth and disgusting style will find in those
writings proofs of a thinking mind.”[521]
He seems to have written a good deal. But the works which will be
remembered the longest are not even mentioned by several of his
biographers. Rose, in his Biographical Dictionary, records works by
him, entitled “Antiquities of the Provincia Romana of Gaul”; “Roman
Antiquities dug up at Bath”; “Observations on the Currents in the
82. Atlantic Ocean”; “Intellectual Physics”; and contributions to the
“Archæologia”: nothing more. To this list Gorton, in his Biographical
Dictionary, adds briefly, “besides many political tracts,” but without
particular reference to the works on America. This is another
instance where the stone rejected by the builders becomes the head
of the corner.
At an early date Pownall comprehended the position of our
country, geographically. He saw the wonderful means of internal
communication supplied by its inland waters, and also the
opportunities of external commerce afforded by the Atlantic Ocean.
On the former he dwells, in a Memorial drawn up in 1756 for the
Duke of Cumberland.[522]
Nobody in our own day, after the
experience of more than a century, has portrayed more vividly the
two vast aqueous masses,—one composed of the Great Lakes and
their dependencies, and the other of the Mississippi and its
tributaries. The Great Lakes are described as “a wilderness of
waters, spreading over the country by an infinite number and variety
of branchings, bays, straits, &c.”[523]
The Mississippi, with its eastern
branch, called the Ohio, is described as having, “as far as we know,
but two falls,—one at a place called by the French St. Antoine, high
up on the west or main branch”; and all its waters “run to the ocean
with a still, easy, and gentle current.”[524]
The picture is completed by
exhibiting the two masses in combination:—
“The waters of each respective mass—not only the
lesser streams, but the main general body of each
going through this continent in every course and
direction—have, by their approach to each other, by
their interlacing with each other, by their
communication to every quarter and in every direction,
an alliance and unity, and form one mass, a one
whole.”[525]
And he remarks, that it is thus seen
83. Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.
More than just a book-buying platform, we strive to be a bridge
connecting you with timeless cultural and intellectual values. With an
elegant, user-friendly interface and a smart search system, you can
quickly find the books that best suit your interests. Additionally,
our special promotions and home delivery services help you save time
and fully enjoy the joy of reading.
Join us on a journey of knowledge exploration, passion nurturing, and
personal growth every day!
ebookbell.com