100% found this document useful (1 vote)
11 views

JavaScript: A Beginner's Guide, Fifth Edition Pollock - eBook PDF instant download

The document is an eBook titled 'JavaScript: A Beginner's Guide, Fifth Edition' by John Pollock, which provides foundational knowledge and practical guidance for learning JavaScript. It includes various resources and links for downloading additional eBooks on related topics. The eBook is published by McGraw-Hill Education and is available in multiple formats.

Uploaded by

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

JavaScript: A Beginner's Guide, Fifth Edition Pollock - eBook PDF instant download

The document is an eBook titled 'JavaScript: A Beginner's Guide, Fifth Edition' by John Pollock, which provides foundational knowledge and practical guidance for learning JavaScript. It includes various resources and links for downloading additional eBooks on related topics. The eBook is published by McGraw-Hill Education and is available in multiple formats.

Uploaded by

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

JavaScript: A Beginner's Guide, Fifth Edition

Pollock - eBook PDF install download

https://ebookluna.com/download/javascript-a-beginners-guide-
fifth-edition-ebook-pdf/

Download more ebook from https://ebookluna.com


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

(eBook PDF) Chemical Dependency Counseling: A Practical


Guide Fifth Edition

https://ebookluna.com/product/ebook-pdf-chemical-dependency-
counseling-a-practical-guide-fifth-edition/

ebookluna.com

(eBook PDF) Learning Web Design: A Beginner's Guide to


HTML, CSS, JavaScript, and Web Graphics 5th Edition

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

ebookluna.com

(eBook PDF) Communicating for Results A Canadian Student's


Guide 5th Fifth Edition

https://ebookluna.com/product/ebook-pdf-communicating-for-results-a-
canadian-students-guide-5th-fifth-edition/

ebookluna.com

(eBook PDF) PMP Project Management Professional Study


Guide, Fifth Edition

https://ebookluna.com/product/ebook-pdf-pmp-project-management-
professional-study-guide-fifth-edition/

ebookluna.com
(eBook PDF) The Norton Field Guide to Writing (Fifth
Edition) 5th Edition

https://ebookluna.com/product/ebook-pdf-the-norton-field-guide-to-
writing-fifth-edition-5th-edition/

ebookluna.com

(Original PDF) New Perspectives on HTML5, CSS3, and


JavaScript 6th Edition

https://ebookluna.com/product/original-pdf-new-perspectives-on-
html5-css3-and-javascript-6th-edition/

ebookluna.com

Joint Structure and Function: A Comprehensive Analysis


Fifth Edition

https://ebookluna.com/product/joint-structure-and-function-a-
comprehensive-analysis-fifth-edition/

ebookluna.com

The entrepreneur's guide to law and strategy Fifth Edition


Craig E. Dauchy - eBook PDF

https://ebookluna.com/download/the-entrepreneurs-guide-to-law-and-
strategy-ebook-pdf/

ebookluna.com

Mike Meyers’ CompTIA A+ Guide the Managing and


Troubleshooting PCs. Fifth Edition (Exams 220-901 &
220-902) Mike Meyers - eBook PDF
https://ebookluna.com/download/mike-meyers-comptia-a-guide-the-
managing-and-troubleshooting-pcs-fifth-edition-
exams-220-901-220-902-ebook-pdf/
ebookluna.com
BeginNew-Tight / JavaScript: A Beginner’s Guide, Fifth Edition / Pollock / 768-0 / Front Matter
Blind Folio: i

JavaScript
A Beginner’s Guide

Fifth Edition
John Pollock

New York Chicago San Francisco


Athens London Madrid Mexico City
Milan New Delhi Singapore
Sydney Toronto

00-FM.indd 1 17/09/19 5:33 PM


Copyright © 2020 by McGraw-Hill Education (Publisher). All rights reserved. Except as permitted under the United States
Copyright Act of 1976, no part of this publication may be reproduced or distributed in any form or by any means, or stored
in a database or retrieval system, without the prior written permission of the publisher, with the exception that the program
listings may be entered, stored, and executed in a computer system, but they may not be reproduced for publication.

ISBN: 978-1-26-045769-8
MHID: 1-26-045769-9

The material in this eBook also appears in the print version of this title: ISBN: 978-1-26-045768-1,
MHID: 1-26-045768-0.

eBook conversion by codeMantra


Version 1.0

All trademarks are trademarks of their respective owners. Rather than put a trademark symbol after every occurrence of a trade-
marked name, we use names in an editorial fashion only, and to the benefit of the trademark owner, with no intention of infringe-
ment of the trademark. Where such designations appear in this book, they have been printed with initial caps.

McGraw-Hill Education eBooks are available at special quantity discounts to use as premiums and sales promotions or for use in
corporate training programs. To contact a representative, please visit the Contact Us page at www.mhprofessional.com.

Oracle and Java are registered trademarks of Oracle Corporation and/or its affiliates. All other trademarks are the property of
their respective owners, and McGraw-Hill Education makes no claim of ownership by the mention of products that contain these
marks.

Screen displays of copyrighted Oracle software programs have been reproduced herein with the permission of Oracle Corpora-
tion and/or its affiliates.

Information has been obtained by Publisher from sources believed to be reliable. However, because of the possibility of human
or mechanical error by our sources, Publisher, or others, Publisher does not guarantee to the accuracy, adequacy, or completeness
of any information included in this work and is not responsible for any errors or omissions or the results obtained from the use
of such information.

TERMS OF USE

This is a copyrighted work and McGraw-Hill Education and its licensors reserve all rights in and to the work. Use of this work
is subject to these terms. Except as permitted under the Copyright Act of 1976 and the right to store and retrieve one copy of the
work, you may not decompile, disassemble, reverse engineer, reproduce, modify, create derivative works based upon, transmit,
distribute, disseminate, sell, publish or sublicense the work or any part of it without McGraw-Hill Education’s prior consent. You
may use the work for your own noncommercial and personal use; any other use of the work is strictly prohibited. Your right to
use the work may be terminated if you fail to comply with these terms.

THE WORK IS PROVIDED “AS IS.” McGRAW-HILL EDUCATION AND ITS LICENSORS MAKE NO GUARANTEES
OR WARRANTIES AS TO THE ACCURACY, ADEQUACY OR COMPLETENESS OF OR RESULTS TO BE OBTAINED
FROM USING THE WORK, INCLUDING ANY INFORMATION THAT CAN BE ACCESSED THROUGH THE WORK VIA
HYPERLINK OR OTHERWISE, AND EXPRESSLY DISCLAIM ANY WARRANTY, EXPRESS OR IMPLIED, INCLUD-
ING BUT NOT LIMITED TO IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR
PURPOSE. McGraw-Hill Education and its licensors do not warrant or guarantee that the functions contained in the work will
meet your requirements or that its operation will be uninterrupted or error free. Neither McGraw-Hill Education nor its licensors
shall be liable to you or anyone else for any inaccuracy, error or omission, regardless of cause, in the work or for any damages
resulting therefrom. McGraw-Hill Education has no responsibility for the content of any information accessed through the work.
Under no circumstances shall McGraw-Hill Education and/or its licensors be liable for any indirect, incidental, special, punitive,
consequential or similar damages that result from the use of or inability to use the work, even if any of them has been advised of
the possibility of such damages. This limitation of liability shall apply to any claim or cause whatsoever whether such claim or
cause arises in contract, tort or otherwise.
BeginNew-Tight / JavaScript: A Beginner’s Guide, Fifth Edition / Pollock / 768-0 / Front Matter
Blind Foli iii

To my wife, Heather, and children, Eva, Elizabeth, Elaine, and Evan,


Bruce and Joy Anderson, and Dr. J. D. and Linda Andrews

In memory of John and Betty Hopkins, James D. and


Livian Anderson, John William and Edith Hopkins,
Burley T. and Aline Price, “Doc” Flores, and Clifton Idom

00-FM.indd 3 17/09/19 5:33


BeginNew-Tight / JavaScript: A Beginner’s Guide, Fifth Edition / Pollock / 768-0 / Front Matter
Blind Foli iv

About the Author


John Pollock is employed as a software developer during
the day and works on Web sites and other projects during
the evening. You can find him on Twitter (@ScripttheWeb)
or LinkedIn (https://www.linkedin.com/in/john-pollock-
82a2b074). John holds a Bachelor of Arts in English from Sam
Houston State University and currently lives in New Waverly,
Texas with his wife, Heather, and children, Eva, Elizabeth,
Elaine, and Evan.

About the Technical Editor


Christie Sorenson is a senior software engineer at ZingChart.
She has worked on JavaScript-based systems since 1997 and
has been fascinated with the evolution of the language. She
has collaborated and been the technical editor on several
JavaScript and HTML books. She holds a Bachelor of Science
in Computer Science from University of California, San Diego,
and now lives in San Francisco with her husband, Luke, and
daughters, Ali and Keira.

00-FM.indd 4 17/09/19 5:33


BeginNew-Tight / JavaScript: A Beginner’s Guide, Fifth Edition / Pollock / 768-0 / Front Matter

Contents
ACKNOWLEDGMENTS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xvi
.
INTRODUCTION . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xvii
.
1 Introduction to JavaScript . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
.
What You Need to Know . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
.
Basic HTML and CSS Knowledge . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
.
Basic Text Editor and Web Browser Knowledge . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
.
Which Version? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
.
Client-Side and Server-Side Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
.
Beginning with JavaScript . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
.
Prototype-Based . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
.
Interpreted Language . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
.
Numerous Environments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
.
Putting It All Together . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
.
Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
.
Try This 1-1: Use JavaScript to Write Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
.
Chapter 1 Self Test ................................................................. 11
.
2 Placing JavaScript in an HTML File ..................................... 15
.
Using the HTML Script Tags ....................................................... 16
.
Identifying the Scripting Language . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
.
Calling External Scripts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
.
v

00-FM.indd 5 17/09/19 5:33


BeginNew-Tight / JavaScript: A Beginner’s Guide, Fifth Edition / Pollock / 768-0 / Front Matter

vi JavaScript: A Beginner’s Guide

Specifying when the Script Should Load . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18

.
Using <noscript></noscript> Tags . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18

.
Creating Your First Script . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20

.
Writing a “Hello World” Script ............................................... 20

.
Creating an HTML Document for the Script .................................. 21

.
Inserting the Script into the HTML Document . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21

.
Try This 2-1: Insert a Script into an HTML Document . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23

.
Using External JavaScript Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24

.
Creating a JavaScript File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24

.
Creating the HTML Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24

.
Viewing the Pages in Your Browser . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26

.
Try This 2-2: Call an External Script from an HTML Document . . . . . . . . . . . . . . . . . . . . . 27

.
Using JavaScript Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
.
Inserting Comments on One Line . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
.
Adding Multiple-Line Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
29
Chapter 2 Self Test ................................................................. 30
.
3 Using Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
Understanding Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
.
Why Variables Are Useful .......................................................... 35
.
Variables as Placeholders for Unknown Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
.
Variables as Time-Savers ..................................................... 35
.
Variables as Code Clarifiers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
.
Defining Variables for Your Scripts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
.
Declaring Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
.
Assigning Values to Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
.
Naming Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
.
Understanding Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
.
Number ...................................................................... 41
.
String . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
.
Boolean . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
.
Null . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
.
Undefined . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
.
Symbol . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
.
Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
.
Try This 3-1: Declare Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
.
Using Variables in Scripts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
.
Making a Call to a Variable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
.
Adding Variables to Text Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
.
Writing a Page of JavaScript . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
.
Creating the Framework . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
.
Defining the Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
.
Adding the Commands ....................................................... 55
.
Modifying the Page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
.
00-FM.indd 6 17/09/19 5:33
BeginNew-Tight / JavaScript: A Beginner’s Guide, Fifth Edition / Pollock / 768-0 / Front Matter

Contents vii

Try This 3-2: Create an HTML Page with JavaScript . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58

.
Chapter 3 Self Test ................................................................. 60

.
4 Using Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63

.
What a Function Is . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64

.
Why Functions Are Useful . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64

.
Structuring Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65

.
Declaring Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65

.
Defining the Code for Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66

.
Naming Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
.
Adding Arguments to Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67

.
Adding Return Statements to Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69

.
Calling Functions in Your Scripts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
.
Script Tags: Head Section or Body Section . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72

.
Calling a Function from Another Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75

.
Calling Functions with Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
.
76
Calling Functions with Return Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
.
Other Ways to Define Functions .............................................. 82
.
Try This 4-1: Create an HTML Page with Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
.
Scope/Context Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
.
Global Context . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
.
Function Context . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
.
Block Context . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
.
Try This 4-2: Write Your Own Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
.
Chapter 4 Self Test ................................................................. 91
.
5 JavaScript Operators ..................................................... 95
.
Understanding the Operator Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
.
Understanding Arithmetic Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
.
The Addition Operator (+) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98
.
The Subtraction Operator (–) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
.
The Multiplication Operator (*) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
.
The Division Operator (/) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
.
The Modulus Operator (%) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
.
The Increment Operator (++) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
.
The Decrement Operator (– –) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104
.
The Unary Plus Operator (+) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
.
The Unary Negation Operator (–) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
.
The Exponentiation Operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106
.
Understanding Assignment Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106
.
The Assignment Operator (=) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
.
The Add-and-Assign Operator (+=) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
.
The Subtract-and-Assign Operator (–=) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108
.
The Multiply-and-Assign Operator (*=) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
.
The Divide-and-Assign Operator (/=) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
.
00-FM.indd 7 17/09/19 5:33
BeginNew-Tight / JavaScript: A Beginner’s Guide, Fifth Edition / Pollock / 768-0 / Front Matter

viii JavaScript: A Beginner’s Guide

The Modulus-and-Assign Operator (%=) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109

.
The Exponent-and-Assign Operator (**=) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109

.
Try This 5-1: Adjust a Variable Value . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110

.
Understanding Comparison Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111

.
The Is-Equal-To Operator (==) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111

.
The Is-Not-Equal-To Operator (!=) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113

.
The Strict Is-Equal-To Operator (===) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114

.
The Strict Is-Not-Equal-To Operator (!==) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114

.
The Is-Greater-Than Operator (>) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114

.
The Is-Less-Than Operator (<) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115

.
The Is-Greater-Than-or-Equal-To Operator (>=) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116

.
The Is-Less-Than-or-Equal-To Operator (<=) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116

.
Understanding Logical Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
.
117
The AND Operator (&&) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
.
The OR Operator (||) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
.
The NOT Operator (!) ........................................................ 118
.
The Bitwise Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118
.
Special Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119
.
Understanding Order of Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120
.
Try This 5-2: True or False? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
.
Chapter 5 Self Test ................................................................. 123
.
6 Conditional Statements and Loops ....................................... 125
.
Defining Conditional Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126
.
What Is a Conditional Statement? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126
.
Why Conditional Statements Are Useful . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
.
Using Conditional Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
.
Using if/else Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
.
Using the switch Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137
.
Using the Conditional Operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139
.
User Input from a Prompt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140
.
Try This 6-1: Work with User Input . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143
.
Defining Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144
.
What Is a Loop? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144
.
Why Loops Are Useful ....................................................... 144
.
Using Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145
.
for . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145
.
while . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 154
.
do while . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 154
.
for in, for each in, and for of . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156
.
Using break and continue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156
.
Try This 6-2: Work with for Loops and while Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 158
.
Chapter 6 Self Test ................................................................. 160
.
00-FM.indd 8 17/09/19 5:33
BeginNew-Tight / JavaScript: A Beginner’s Guide, Fifth Edition / Pollock / 768-0 / Front Matter

Contents ix

7 JavaScript Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163

.
What Is an Array? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164

.
Why Arrays Are Useful . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165

.
Defining and Accessing Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165

.
Naming an Array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165

.
Defining an Array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165
Accessing an Array’s Elements ............................................... 167

.
Using the length Property and Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168

.
Changing Array Values and Changing the Length ............................. 169

.
Try This 7-1: Use Loops with Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171

.
Array Properties and Methods ...................................................... 172
.
Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172
Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173
.
Nesting Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189
.
Defining Nested Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189
.
Loops and Nested Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 190
.
Try This 7-2: Nested Arrays Practice . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 192
.
Chapter 7 Self Test ................................................................. 193
.
8 Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195
.
Defining Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196
.
Creating Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196
.
Naming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196
.
Single Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197
.
Try This 8-1: Create a Computer Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 200
.
Object Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201
.
Constructor Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201
.
Using Prototypes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 206
.
The class Keyword ........................................................... 209
.
Helpful Statements for Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210
.
The for-in Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210
.
The with Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211
.
Try This 8-2: Practice with the Combination Constructor/Prototype Pattern . . . . . . . . . . 212
.
Understanding Predefined JavaScript Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213
.
The Navigator Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214
.
The History Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 216
.
Chapter 8 Self Test ................................................................. 218
.
9 The Document Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221
.
Defining the Document Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 222
.
Using the Document Object Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223
Using the Properties of the Document Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223
Collections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 225
.
The cookie Property . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226
.
00-FM.indd 9 17/09/19 5:33
BeginNew-Tight / JavaScript: A Beginner’s Guide, Fifth Edition / Pollock / 768-0 / Front Matter

x JavaScript: A Beginner’s Guide

The dir Property . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226

.
The lastModified Property . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226

.
The referrer Property ......................................................... 227

.
The title Property . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 228

.
The URL Property . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229

.
The URLUnencoded Property . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229
Using the Methods of the Document Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230

.
The get Methods for Elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230

.
The open() and close() Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235

.
The write() and writeln() Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237

.
Using DOM Nodes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 238
.
DOM Node Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
.
238
DOM Node Methods ......................................................... 241
.
Try This 9-1: Add a DOM Node to the Document . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 246

.
Creating Dynamic Scripts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 247
.
Styles in JavaScript . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 247
.
Simple Event Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 249
.
Coding a Dynamic Script . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 250
.
Try This 9-2: Try Out Property Changes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 252
Chapter 9 Self Test ................................................................. 253
.
10 Event Handlers ........................................................... 255
.
What Is an Event Handler? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 256
.
Why Event Handlers Are Useful . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 256
.
Understanding Event Handler Locations and Uses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257
.
Using an Event Handler in an HTML Element . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257
.
Using an Event Handler in the Script Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 259
.
Learning the Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 260
.
The Click Event . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 262
.
Focus and Blur Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263
.
The Load and Unload Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 265
.
The Reset and Submit Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 268
.
The Mouse Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 269
.
The Keyboard Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 269
.
Try This 10-1: Focus and Blur . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 270
.
Other Ways to Register Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 272
.
The addEventListener() Method .............................................. 272
.
The attachEvent() Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 274
.
The Event Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 274
.
DOM and Internet Explorer: DOM Level 0 Registration . . . . . . . . . . . . . . . . . . . . . . . 274
.
Using event with Modern Event Registration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 275
.
Properties and Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 276
.
Event Information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 277
.
Try This 10-2: Using addEventListener() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 278
.
00-FM.indd 10 17/09/19 5:33
BeginNew-Tight / JavaScript: A Beginner’s Guide, Fifth Edition / Pollock / 768-0 / Front Matter

Contents xi

Creating Scripts Using Event Handlers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 278

.
Show Hidden Content ........................................................ 279

.
Change Content .............................................................. 280

.
Custom Events ............................................................... 284

.
Chapter 10 Self Test . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 286

.
11 Introduction to Node.js ................................................... 289

.
Introducing Node.js . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 290
.
Installing Node.js . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 291
.
Check for a Current Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 291

.
Install Node.js . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 292
.
Write a “Hello World” Script ................................................. 292

.
Using Node Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 295
.
Using Native Node Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
.
295
Asynchronous Execution ..................................................... 296
.
Non-Native Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 298
.
Try This 11-1: Use a Custom Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 301
.
Installing a Database . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 301
.
Database Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 302
.
Install PostgreSQL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 302
.
Create a Database Using pgAdmin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 303
.
Try This 11-2: Test Some SQL Queries ............................................. 312
.
Creating a Web Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 313
.
Chapter 11 Self Test . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 315
.
12 Math, Number, and Date Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 317
.
Using the Math Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 318
.
What Is the Math Object? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 318
.
How the Math Object Is Useful . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 318
.
Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 318
Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 321
.
Try This 12-1: Display a Random Link on a Page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 334
.
Understanding the Number Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 335
.
Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 335
Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 337
.
Using the Date Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 340
.
Properties and Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 340
.
Methods That Get Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 342
.
Methods That Set Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 345
.
Other Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 345
.
How About Some Date Scripts? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 346
.
Try This 12-2: Create a JavaScript Clock . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 350
.
Continuing Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 351
.
Getting to the Needed Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 352
.
Running Some Calculations on the Results . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 353
.
Chapter 12 Self Test . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 355
.
00-FM.indd 11 17/09/19 5:33
BeginNew-Tight / JavaScript: A Beginner’s Guide, Fifth Edition / Pollock / 768-0 / Front Matter

xii JavaScript: A Beginner’s Guide

13 Handling Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 357

.
Introduction to the String Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 358

.
The String Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 358

.
The String Literal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 359

.
What’s the Difference? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 359

.
Using the Properties and Methods of the String Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 360

.
The length Property . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 360

.
Methods of the String Object ....................................................... 360

.
Try This 13-1: Use indexOf() to Test an Address . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 370

.
Using Cookies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 371
.
Setting a Cookie . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 372
.
Reading a Cookie . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 374
.
Try This 13-2: Remember a Name . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
.
376
Using Regular Expressions ......................................................... 377
.
Creating Regular Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 377
.
Testing Strings Against Regular Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 378

.
Adding Flags . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 379
.
Creating Powerful Patterns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 380
.
Grouping Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 384
.
The replace(), match(), matchAll(), and search() Methods . . . . . . . . . . . . . . . . . . . . . 384

.
More Information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 387
.
Continuing Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 387
.
Chapter 13 Self Test . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 389
.
14 Browser-Based JavaScript ................................................ 391
.
Window: The Global Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 392
.
Using the Properties of the Window Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 393
.
The closed Property . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 394
The frames Property . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 395
.
The innerWidth and innerHeight Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 395
.
The length Property . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 395
.
The location Property . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 395
.
The name Property ........................................................... 396
.
The opener Property . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 396
.
The parent, self, and top Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 397
.
The status and defaultStatus Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 397
.
Try This 14-1: Use the location and innerWidth Properties .......................... 398
.
Using the Methods of the Window Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 399
.
The alert(), prompt(), and confirm() Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 400
The print() Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 401
.
The setInterval() and clearInterval() Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 403
The setTimeout() and clearTimeout() Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 404
.
Try This 14-2: Use the setTimeout() and confirm() Methods . . . . . . . . . . . . . . . . . . . . . . . . . 406
.
00-FM.indd 12 17/09/19 5:33
BeginNew-Tight / JavaScript: A Beginner’s Guide, Fifth Edition / Pollock / 768-0 / Front Matter

Contents xiii

The Main Window and New Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 407

.
The Tale of Pop-up Windows ................................................. 407

.
Opening New Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 408

.
Closing New Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 411

.
Moving, Resizing, and Scrolling New Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 412

.
The resizeBy() and resizeTo() Methods ....................................... 416

.
The scrollBy() and ScrollTo() Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 418

.
Working with Images . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 418
.
Rollovers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 418
.
JavaScript and Frames . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
.
420
Purpose of Frames . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 420
.
Accessing Frames . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 420
.
Breaking Out of Frames ...................................................... 423
.
Using iFrames . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 424
.
Chapter 14 Self Test . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 424
.
15 JavaScript Forms and Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 427
.
Accessing Forms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 428
.
Using the forms Array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 428
.
Using an ID .................................................................. 431
.
Using the Properties and Methods of the Form Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 433
.
Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 433
Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 436
.
Ensuring the Accessibility of Forms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 438
.
Using Proper Element and Label Order ....................................... 438
.
Using <label></label> Tags . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 438
.
Using <fieldset></fieldset> Tags . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 439
.
Not Assuming Client-Side Scripting .......................................... 439
.
Validation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 440
.
Simple Validation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 440
.
Techniques . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 441
.
Check Boxes and Radio Buttons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 442
.
Try This 15-1: Request a Number . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 445
.
HTML5 and Forms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 446
.
New Elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 446
.
New Input Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 450
.
New Attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 452
.
HTML5 Form Validation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 452
.
Try This 15-2: Validate a Phone Number with HTML5 or JavaScript ................ 455
.
AJAX and JSON . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 456
.
AJAX ........................................................................ 456
.
JSON . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 462
.
Chapter 15 Self Test . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 465
.
00-FM.indd 13 17/09/19 5:33
BeginNew-Tight / JavaScript: A Beginner’s Guide, Fifth Edition / Pollock / 768-0 / Front Matter

xiv JavaScript: A Beginner’s Guide

16 Further Browser-Based JavaScript . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 469

.
Using jQuery . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 470

.
Obtaining jQuery . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 470

.
Getting Started: document.ready() ............................................ 471

.
Using Selectors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 471

.
Altering Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 473

.
Methods for Effects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 475

.
Further Reading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 477
.
Try This 16-1: Use jQuery to Create Effects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 477

.
Debugging Scripts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 479
.
Types of Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 479
.
Using the Console . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 482
.
Using a Lint Tool . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 483
.
Browser Developer Tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 484
.
JavaScript and Accessibility . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 485
.
Separate Content from Presentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
486
Enhancing Content ........................................................... 488
.
Try This 16-2: Make This Code Accessible . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 488
.
JavaScript Security . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 489
.
Page Protection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 490
.
JavaScript and APIs from HTML ................................................... 492
.
The <canvas> Element . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 492
.
Drag and Drop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 498
.
Try This 16-3: Drag and Drop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 502
.
Node.js App Completion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 503
.
Update the Node.js Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 503
Update the Front-end Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 504
.
Need Help? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 508
.
Chapter 16 Self Test . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 509
.
A Answers to Self Tests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 511
.
Chapter 1: Introduction to JavaScript . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 512
.
Chapter 2: Placing JavaScript in an HTML File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 512
.
Chapter 3: Using Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 513
.
Chapter 4: Using Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 513
.
Chapter 5: JavaScript Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 514
.
Chapter 6: Conditional Statements and Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 515
.
Chapter 7: JavaScript Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 515
.
Chapter 8: Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 516
.
Chapter 9: The Document Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 517
.
00-FM.indd 14 17/09/19 5:33
BeginNew-Tight / JavaScript: A Beginner’s Guide, Fifth Edition / Pollock / 768-0 / Front Matter

Contents xv

Chapter 10: Event Handlers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 517

.
Chapter 11: Introduction to Node.js . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 518

.
Chapter 12: Math, Number, and Date Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 519

.
Chapter 13: Handling Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 519

.
Chapter 14: Browser-Based JavaScript . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 520

.
Chapter 15: JavaScript Forms and Data ....................................... 521

.
Chapter 16: Further Browser-Based JavaScript . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 521

.
Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 523

.
00-FM.indd 15 17/09/19 5:33
BeginNew-Tight / JavaScript: A Beginner’s Guide, Fifth Edition / Pollock / 768-0 / Front Matter
Blind Folio vi

Acknowledgments
I would like to begin by thanking my wonderful wife, Heather Pollock, for all of her love,
support, and encouragement in all I do. I love you! I would also like to thank my three
daughters, Eva, Elizabeth, and Elaine, as well as my son, Evan. I love all of you!
I would like to thank my parents, Bruce and Joy Anderson, for their love and guidance, and
for always supporting my endeavors.
I would like to thank Dr. J. D. and Linda Andrews for their love, guidance, and support.
In addition, I would like to thank Richard Pollock (brother) and family, Misty Castleman
(sister) and family, Warren Anderson (brother) and family, Jon Andrews (brother) and family,
Lisa and Julian Owens (aunt/uncle) and family, and every aunt, uncle, cousin, or other relation
in my family. All of you have been a great influence in my life.
I would like to thank all of my editors at McGraw-Hill for their outstanding help and
support throughout the writing of this book. Thanks to Lisa McClain, Emily Walters, Claire Yee,
Snehil Sharma, Sarika Gupta, Bart Reed, and to all the editors who worked on this and previous
editions of the book.
Thanks to my technical editor, Christie Sorenson, for editing and checking over all the
technical aspects of the book and for helping me provide clear explanations of the topics that
are covered.
I would like to thank God for the ability He has given me to help and teach people by my
writing. “In all your ways acknowledge Him, and He shall direct your paths.” (Proverbs 3:6)

xvi

00-FM.indd 16 17/09/19 5:33


BeginNew-Tight / JavaScript: A Beginner’s Guide, Fifth Edition / Pollock / 768-0 / Front Matter

Introduction
W elcome to JavaScript: A Beginner’s Guide, Fifth Edition! Years ago, I was surfing
the Web and noticed that people were publishing pages about themselves and calling
them homepages. After viewing a number of these, I decided to create a homepage myself. I
had no idea where to begin, but through trial and error I figured out how to code HTML and
publish my documents on a Web server. Over time, I saw some interesting effects used on other
homepages (like alert messages that popped up out of nowhere or images that would magically
change when I moved my mouse over them). I was curious and just had to know what was being
done to create those effects. Were these page creators using HTML tags I did not know about?
Eventually, one site revealed what was being used to create those effects: JavaScript. I
went in search of information on it and came across a few tutorials and scripts on the Web.
Since I had programmed in other languages (such as a relatively obscure language called Ada),
I was able to catch on to JavaScript fairly quickly by looking at these tutorials and scripts.
I learned enough that I decided to create a Web site that would teach HTML and JavaScript
to beginners. As soon as I began the project, I received questions from visitors that were
way over my head—forcing me to dig deeper and learn more about JavaScript. As a result,
I became completely familiar with this scripting language and what it can do. Not only can
you add fun effects to a Web page, you can create scripts that will perform useful tasks, like
validate form input, add navigational elements to documents, and react to user events.
The goal of this book is to help you to learn the basics of the JavaScript language with as
little hair pulling and monitor smashing as possible. You do not need any prior programming
experience to learn JavaScript from this book. All you need is knowledge of HTML and/or
XHTML, Cascading Style Sheets (CSS), and how to use your favorite text editor and Web
browser (see Chapter 1 for more information).

xvii

00-FM.indd 17 17/09/19 5:33


BeginNew-Tight / JavaScript: A Beginner’s Guide, Fifth Edition / Pollock / 768-0 / Front Matter

xviii JavaScript: A Beginner’s Guide

What This Book Covers


The 16 chapters of this book cover specific topics on the JavaScript language. The first two
chapters cover the most basic aspects of the language: what it is, what you need to know to
begin using JavaScript, and how to place JavaScript into an HTML file. The middle of the
book (Chapters 3–14) covers beginning JavaScript topics from variables all the way to using
JavaScript with forms. The final two chapters (Chapters 15–16) introduce some advanced
techniques, and point you toward resources if you want to learn more about JavaScript once
you have completed the book.
This book includes a number of special features in each chapter to assist you in learning
JavaScript. These features include

● Key Skills & Concepts Each chapter begins with a set of key skills and concepts that
you will understand by the end of the chapter.
● Ask the Expert The Ask the Expert sections present commonly asked questions about
topics covered in the preceding text, with responses from the author.
● Try This These sections get you to practice what you have learned using a hands-on
approach. Each Try This will have you code a script through step-by-step directions
on what you need to do to in order to accomplish the goal. You can find solutions to
each project on the McGraw-Hill Professional Web site at www.mhprofessional.com/
computingdownload.
● Notes, Tips, and Cautions These elements call your attention to noteworthy statements
that you will find helpful as you move through the chapters.
● Code Code listings display example source code used in scripts or programs.
● Callouts Callouts display helpful hints and notes about the example code, pointing to the
relevant lines in the code.
● Self Test Each chapter ends with a Self Test, a series of 15 questions to see if you have
mastered the topics covered in the chapter. The answers to each Self Test can be found in
the appendix.

That is it! You are now familiar with the organization and special features of this book to
start your journey through JavaScript. If you find that you are stuck and need help, feel free to
contact me with your questions. To contact me, you can reach me on LinkedIn (https://www
.linkedin.com/in/john-pollock-82a2b074) or you can find me on Twitter (@ScripttheWeb).
Now it is time to learn JavaScript. Get ready, get set, and have fun!

00-FM.indd 18 17/09/19 5:33


BeginNew-Tight / JavaScript: A Beginner’s Guide, Fifth Edition / Pollock / 768-0

Chapter 1
Introduction to JavaScript

01-ch01.indd 1 27/09/19 9:56


BeginNew-Tight / JavaScript: A Beginner’s Guide, Fifth Edition / Pollock / 768-0

2 JavaScript: A Beginner’s Guide

Key Skills & Concepts


● Using Text Editors, WYSIWYG Editors, and Web Browsers
● Defining JavaScript
● Differences Between Client-Side and Server-Side Programming

W elcome to JavaScript: A Beginner’s Guide, Fifth Edition! You’re obviously interested in


learning JavaScript, but perhaps you’re not sure what you need to know to use it. This
chapter answers some basic questions about what JavaScript is, provides a brief history of the
language, and discusses the various environments that can use JavaScript for programming.
JavaScript is ubiquitous on the World Wide Web. You can use JavaScript both to make
your Web pages more interactive, so that they react to a viewer’s actions, and to give your Web
pages some special effects (visual or otherwise). JavaScript can now even be used to perform
input/output operations or build Web servers by using Node.js!
JavaScript often gets included with Hypertext Markup Language (HTML) and Cascading
Style Sheets (CSS) as the three recommended languages for beginning Web developers
(whether you build Web sites for business or pleasure). Of course, you can build a Web page
by using only HTML and CSS, but JavaScript allows you to add additional features that a
static page of HTML can’t provide without some sort of scripting or programming help.

What You Need to Know


Before you begin learning about JavaScript, you should have (or obtain) a basic knowledge of
the following:

●● HTML and Cascading Style Sheets (CSS)


●● Text editors and Web browsers
●● The different versions of JavaScript
●● Differences in client-side and server-side programming

If you have this basic knowledge, you’ll do just fine as you work through this book. Knowing
another programming/scripting language or having previous experience with JavaScript isn’t
required. This book is a beginner’s guide to JavaScript.
If you think you don’t have enough experience in one of the aforementioned areas, a closer
look at each one may help you decide what to do.

01-ch01.indd 2 27/09/19 9:56


BeginNew-Tight / JavaScript: A Beginner’s Guide, Fifth Edition / Pollock / 768-0

Chapter 1: Introduction to JavaScript 3

Basic HTML and CSS Knowledge


While you don’t need to be an HTML guru, you do need to know where to place certain
elements (like the head and body elements) and how to add your own attributes. This book
will reference scripts in the head section (between the <head> and </head> tags) and the body
section (between the <body> and </body> tags).
Sometimes, you will also need to add an attribute to a tag for a script to function properly.
For example, you may need to name a form element using the id attribute, as shown in the
following code:
<input type="text" id="thename">

If you know the basics of using tags and attributes, the HTML portion shouldn’t pose any
problems in learning JavaScript.
If you don’t have a basic knowledge of HTML, you can learn it fairly quickly through
a number of media. For example, you can buy a book or look for some helpful information
on the Web. A good book is HTML: A Beginner’s Guide, Fifth Edition by Wendy Willard
(McGraw-Hill, 2013). To find information about HTML on the Web, check out developer
.mozilla.org/en-US/docs/Learn/HTML/Introduction_to_HTML/Getting_started.
Occasionally, you will need to use CSS to add or change presentation features on a Web page.
We will mainly use CSS for the purposes of dynamically changing CSS properties via
JavaScript in this book. A good place to learn CSS is developer.mozilla.org/en-US/docs/Learn/
CSS/Introduction_to_CSS/How_CSS_works.

Basic Text Editor and Web Browser Knowledge


Before jumping in and coding with JavaScript, you must be able to use a text editor or HTML
editor, and a Web browser. You’ll use these tools to code your scripts.

Text Editors
A number of text editors and HTML editors support JavaScript. If you know HTML, you’ve
probably already used an HTML editor to create your HTML files, so you might not have
to change.
However, some HTML editors have problems related to adding JavaScript code (such as
changing where the code is placed or altering the code itself when you save the file). This is
more often the case when using WYSIWYG (What You See Is What You Get) editors. It is
best to use a code editor such as Sublime or Visual Studio Code (recommended) or a plain text
editor. Some examples of text editors are Notepad, TextPad, and Simple Text.

Web Browsers
Again, if you’ve been coding in HTML, you probably won’t need to change your browser.
However, some browsers have trouble with the newer versions of JavaScript. The choice of

01-ch01.indd 3 27/09/19 9:56


BeginNew-Tight / JavaScript: A Beginner’s Guide, Fifth Edition / Pollock / 768-0

4 JavaScript: A Beginner’s Guide

Web browser is ultimately up to you, as long as it’s compatible with JavaScript. I recommend
the latest version of one of following browsers to test your JavaScript code:

●● Google Chrome
●● Mozilla Firefox
●● Microsoft Edge

New versions of these browsers continue to be produced. The newest versions will continue
to support more features.
To give you an idea of what some browsers look like, Figure 1-1 shows a Web page when
viewed in Chrome, and Figure 1-2 shows a Web page when viewed in Mozilla Firefox.
If you have an older browser and you can’t upgrade, a number of features (mostly discussed
later in the book) may not work in that browser. Even so, the book can still help you learn the
JavaScript language itself (especially when you’re using Node.js instead of a browser), so you
don’t need to give up if you have an older browser.

Figure 1-1 A Web page viewed in Google Chrome


 
01-ch01.indd 4 27/09/19 9:56
BeginNew-Tight / JavaScript: A Beginner’s Guide, Fifth Edition / Pollock / 768-0

Chapter 1: Introduction to JavaScript 5

Figure 1-2 A Web page viewed in Mozilla Firefox


 
NOTE
Even if you have one of the latest browsers, your web site viewers may not, so it
is always appropriate to understand what features may not be supported in older
browsers. This book will cover how to handle a number of these issues.

Which Version?
The version of JavaScript being used by a browser is typically associated with what version
of ECMAScript it supports. You can see what ECMAScript versions are supported by each
browser at kangax.github.io/compat-table/es6/.
ECMAScript is the international standard name and specification used for the JavaScript
language, so it’s not a new language but a standard that is set for JavaScript, JScript, and other
implementations of the language. For more on ECMAScript, see www.ecma-international.org/
publications/standards/Ecma-262.htm.
At the time of this writing, the browsers recommended earlier in this chapter should support
at least ECMAScript 7. Node.js uses the V8 JavaScript engine, and the latest version of Node.js
should also support at least ECMAScript 7.

01-ch01.indd 5 27/09/19 9:56


BeginNew-Tight / JavaScript: A Beginner’s Guide, Fifth Edition / Pollock / 768-0

6 JavaScript: A Beginner’s Guide

Remember, It’s Not Java


JavaScript and Java are two different languages. Java is a programming language that must be
compiled (running a program through software that converts the higher-level code to machine
language) before a program can be executed. More information on the Java language can be
found at docs.oracle.com/javase/tutorial/.

Similarities to Other Languages


JavaScript does have similarities to other programming and scripting languages. If you
have experience with Java, C++, or C, you’ll notice some similarities in the syntax, which
may help you to learn more quickly. Because it’s a scripting language, JavaScript also has
similarities to languages like PHP—which can also be run through an interpreter rather than
being compiled.
If you have programming or scripting experience in any language, it will make learning
JavaScript easier—but it isn’t required.

Client-Side and Server-Side Programming


The addition of Node.js allows JavaScript to be run on the server side in addition to its traditional
space on the client side. Learning a little about these different environments will help you to
understand the type of programming that will need to be done when working on the client side
versus working on the server side.
A client-side language is run directly through the client being used by the viewer. In the
case of client-side JavaScript, the client is typically a Web browser. Therefore, client-side
JavaScript is run directly in the Web browser and doesn’t need to handle any requests on a Web
server. The limitation is that client-side JavaScript cannot directly save information (though it
can send information to a server-side program to do so).

NOTE
Using the XMLHttpRequest object and the Fetch API allows JavaScript to send and
request data from the server. These will be covered briefly in Chapter 14.

A client-side language is useful for tasks that deal with the content of a document or that
allow information to be validated before it is sent to a server-side program or script. For instance,
JavaScript can change the content of one or more elements on a Web page when the user clicks a
link or presses a button (many other user actions can also be activated).
JavaScript can also be used to check the information entered into a form before the form
is sent to a server-side program to be processed. This information check can prevent strain
on the Web server by not allowing submissions with inaccurate or incomplete information.
Rather than the program running on the server until the information is correct, that data can
be sent to the server just once with correct information. This also benefits the user, since
client-side validation can provide feedback much more quickly to allow the user to make any
corrections.

01-ch01.indd 6 27/09/19 9:56


Other documents randomly have
different content
drunken they became the more he flogged them; but the crime and
punishment seemed to react on each other, and the ship became at
last so very notorious for the cat that he was jested upon it by his
fellow captains, and the men deserted at every opportunity.”
I believe the experience, thus presented, of these two ships, to be a
fair exposition of the general and direct tendency of the two
systems. Revolting as punishment with the ‘colt’ and ‘cat’ ever has
been to me, and often as my blood has been made to boil in
witnessing it, a want of practical knowledge in the case led me, for a
time, reluctantly to acquiesce in the opinion universally held, so far
as I could discover, by those most experienced in naval rule, that it
was indispensable as a means of discipline on board a man-of-war.
But the teachings of my nature, that this is an error, have been
corroborated by long observation; and had no previous conviction of
this been fastened on my mind, the success of the executive officer
of the Congress in devising and substituting more humanizing modes
of punishment for transgressions of law and delinquencies in duty,
would have gone far in persuading me to it. I doubt not that should
the law of the lash be abrogated by our national legislature to-
morrow,[1] and the change be met by the enactment of a wise and
philanthropic code of naval rule, the discipline and efficiency of the
service would be more perfect than ever before.

1. Flogging was abolished, both in the navy and mercantile


marine, a few months after the above was written.

June 24th.—
“The twilight is sad and cloudy,
The wind blows wild and free,
And like the wings of sea-birds
Flash the white caps of the sea.”
So sings Longfellow, and such is the imagery around us from the
passing of a heavy squall. The rushing wind and the dampness
brought with it, from the approaching rain, are welcome and most
refreshing, after two or three days and nights on the south side of
Cuba, sultry almost to suffocation. Whether correct in our
recollections or not, all hands agree that, in no part of the world in
which we have been, either on land or at sea, have we before
suffered so much from the intensity of the heat. Notwithstanding, I
was never in the enjoyment of more vigorous health or in more
elastic spirits.
In the afternoon of my last date, we had a distant view of a part of
the island of Jamaica, as well as of San Domingo and Cuba: a sail,
too, was in sight, and the smoke of a steamer marked on the
horizon—all taking much from the solitariness of our position. The
next morning we were slowly advancing westward, along the lofty,
but mist covered and cloud obscured mountain range of the Sierra
de Cobra, beneath a point in which lie the port and city of St. Jago
de Cuba. At sunset the same evening we were directly abreast Cape
de Cruz, in full view of the coast, but at too great a distance to make
out the distinctive features of the landscape, even with the best
glasses. We are now off the Isle of Pines, famed in the annals of the
Buccaneers of the olden time, and a haunt of pirates in our own day.
Light and baffling winds, with alternate calms, have made our
progress slow. The tedium of the time has been relieved in part by a
first interchange of dinner parties between the wardroom mess and
the commodore and captain. The kindest feeling exists among the
officers of all grades on board, and these reunions, where the
formality of official intercourse gives place for the time to the free
interchange of thought and feeling, and of sympathy in intellect and
taste, are salutary in their influences on both mind and heart. The
Sabbath is the day usually chosen on board a man-of-war for these
courtesies; but it has been unanimously decided, by our mess, that
the entertainments given in the wardroom shall be on a week day.
During the continuance of moonlight in the evening and early part of
the night, the enjoyment of it on deck in quiet musings, after the
heat of the day, seemed the prevailing mood of the ship’s company.
The band in whole or in part, at times, added music to the
sympathies which were sending our thoughts and affections
homeward by the way of the moon. But now that she is on the
wane, and reserves her beams for the later watches of the night, the
sailors cheer themselves in the darkness, by singing on the spar-
deck, grouped in their respective limits from the fife-rail to the
forecastle. Last evening, even the quarter-deck was invaded, under
the sanction of an officer, by a party of negro minstrels: not such
mock performers as are heard on shore under the name, but of the
genuine type, consisting of the servants of the wardroom. For half
an hour or more they sang, in practised harmony and with effect,
many of the more sentimental and popular of the negro melodies;
while forward and in the gangways there was echoed forth, in varied
song, the feats of warrior knights and the love of ladies fair. Others
of the crew were, at the same time, listening in groups between the
guns along the entire deck, to a rehearsal by their shipmates of
tragic stories of shipwreck, piracy and murder; to recitations from
tragedies and comedies; to close arguments on various topics—
navigation and seamanship, politics, morals and religion—and, at
one point, to a lecture on history, of which I overheard enough to
learn the subject to be the life and achievements of the brave
Wallace, dilated upon in the broad dialect of the “land o’ cakes!”
Light-heartedness and contentment seem every where to prevail,
and all manifest by their conduct, as well as by word, that they feel
themselves to be on board a favored ship.
Had I time for the record, you would be amused by many things I
hourly hear and see, in my walks of leisure. To-day, while on the
quarter-deck after the men’s dinner, I overheard one of the
messenger boys, who had just come from this meal, say to a
companion, “I tell you what, Jim, I couldn’t eat much of that dinner:
old mahogany and hard tack, is what I call pretty tough eating. To-
morrow too is bean day, and I wouldn’t give a penny for a bushel of
them.” A sprightly young sailor who completed an apprenticeship in
the service, happening to pass at the time, stopped for a moment,
and with an assumed air of indignant reproof, exclaimed, “Why, you
ungrateful young cub!—you growling at Uncle Sam’s grub? why you
ought to be down upon your knees thanking God that you have so
good an uncle to give you any thing!”
Just afterwards, I fell into conversation with an old salt who had
been with me, in the Delaware line-of-battle ship, in 1833. After
mutual inquiries of various officers and men who were shipmates
with us then; what had become of this one and what of that—he
said, in all honesty of heart, and with a most lugubrious expression
of face, “And there was Lieut. M—— too: they tell me, sir, he
stepped out entirely, the other day at the Hospital!”—meaning that
he had died there. I never heard the expression in such a connection
before, and could not avoid being struck, not only with its oddity, but
also with its force.
June 29th.—Just at nightfall, on my last date, we doubled Cape
Antonio, the extreme westerly point of Cuba, at a distance of ten or
twelve miles. It is long and low, covered with dark woods, and, in
general aspect, not unlike the coasts of Long Island and New Jersey,
as seen from the sea. As soon as our course was turned northward
for Havana, the regular wind became adverse to us, and the next
morning we were in the Florida Channel, far from the land and a
hundred miles and more from our port. The tediousness of a dead
beat to windward was relieved, however, by the greater freshness
and elasticity of the air, in comparison with that on the south side of
Cuba. For two or three evenings, here, the sunsets were among the
most gorgeous I recollect. The whole western hemisphere, filled with
fantastic and richly colored clouds, glowed with a brilliancy and glare
of crimson light, as if the entire sea beneath were one vast bed of
volcanic fire.
After two days we again made the land, with fine views during the
afternoon, of two lofty ranges of mountains in the interior of the
island—the Sierra del Rosario and the Sierra de los Organos or
Organ mountains; but it was not till last night that we reached the
parallel of Havana. At 10 o’clock the Moro light, at the entrance of
the port, was descried, some fifteen miles distant. Its brilliant
flashings, through the darkness of an unsettled sky, came cheerily
upon the sight over the troubled water, in the assurance they gave
of our true position, amid the changing currents and hazardous
navigation of these straits.
Before daybreak this morning we fell in with and spoke the sloop-of-
war Germantown, Captain Lowndes, cruising off the harbor. I was
early on deck. The morning was fresh and beautiful, but the shores
less bold and striking than I had anticipated; and the mountains in
view were more remote. Still the landscape was pleasing in its
verdure, though neither varied nor picturesque in its outline. Having
been lying to for the night, we were still eight or ten miles from the
entrance of the harbor; but the Moro Castle and city were in distinct
view—the former, surmounted by its pharos towering loftily on a
precipitous cliff of rock on the left of the entrance, and the latter
stretching beneath it to the right, in a long line of whiteness on a
level with the sea.
The scene increased momentarily in interest. A fresh trade-wind,
creating a sea which, in the brightness of the sun, tossed up jets of
diamonds on every side, hurried us rapidly forward, under topsails
and topgallant-sails only: the Germantown, a beautiful craft,
followed closely in our wake, fluttering over the water with the
lightness and buoyancy of a bird. There were besides some eight or
ten square-rigged merchant vessels in sight, under various degrees
of sail—some entering and others leaving port. While in the midst of
these, the Germantown and Congress interchanged salutes, with
pretty effect on the general picture.
The wind had now increased to a half gale; a pilot had boarded us,
and we bore away with a rush for the Moro, which immediately
overhangs the entrance to the port. This is narrow—very narrow;
seemingly a mere creek, a few ships’ length only in width. It runs at
right angles with the line of coast along which we were flying. This
made it necessary in entering, to haul suddenly, from a free course,
closely on the wind. We did so, at the speed of a race-horse, almost
grazing the surf-lashed rocks over which tower the frowning
battlements of the Moro, and within biscuit throw, as it were, of the
batteries of the Punta on the opposite side—the pilot, momentarily
alternating the exclamation “Hard a port!” “Hard a starboard!”
“Steady—steady!” kept the men at the helm on the full spring in
shifting the wheel from side to side; while at the same time the
yards were filled with the crew reducing sail to bare poles, as if by
magic, under the trumpet orders of the first lieutenant. I thought it
one of the most exciting moments, and one of the most beautiful
sights, in the navigation of so large a ship, I had ever witnessed.
In less time than is required thus to state it, we were transferred
from the tossings of a rough sea, to the glassy surface of an
apparent river. The scene on either hand was picturesque and
animated. On one side, were the terraced heights adjoining the
Moro, grim with the defences of war, relieved here and there by
sentries and groups of soldiers, lounging about the batteries; and,
on the other, level with the water, a range of stone quays, lined with
shipping and coasting craft, and covered with sailors, boatmen,
negro porters, and stevedores. Beyond rose the buildings of the city,
painted in every variety of light and gay colors, and overtopped by
the time-stained domes and towers of the churches and other public
structures. The aspect of the whole was so entirely transatlantic,
that I could scarce resist the illusion that I was again in old Spain,
and that it was “fair Cadiz” I saw stretched before me. The gallantry
of our entrance had attracted the gaze of the thousands crowding
the quay in its whole length, and murmurs of admiration were every
where heard at the beauty of our frigate, and the dashing style in
which she glided rapidly along under the headway brought in by her
from the sea.
At the end of half a mile, the straight and narrow inlet expands into
a round basin, five or six miles in circumference. Near the centre of
this we dropped anchor: having the city and its defences towards
the sea on one side of us, and green hills tufted with palm-trees and
dotted with cottages and country seats on the other. The harbor is a
gem of beauty, capable of containing the navies of half the world.
Five Spanish men-of-war, including a ship-of-the-line, are moored
within pistol shot of us, and the Germantown immediately at our
stern. The dropping of the anchor was followed by salutes from our
batteries of twenty-one guns to the flag of Spain, seventeen to that
of the Spanish admiral, in command, and nine in honor of Mr.
Campbell, the American consul, who soon boarded the Congress.
CHAPTER III.

Havana.

July 1st.—The object of a visit by the Congress to Cuba, before


proceeding to her station on the coast of Brazil, is to bring to a close
the negotiations which have been for some time pending with the
authorities here, in reference to our filibustering compatriots, the
prisoners of Contoy.
The report made by Captain Lowndes of the Germantown, on
boarding us in the offing, and by Mr. Campbell afterwards, of the
state of public feeling in reference to these, and to the citizens of
the United States in general, led us to apprehend there would be
great difficulty in securing an amicable arrangement of the point at
issue—the disposition to be made of the prisoners. The excitement
and indignation of the Spanish population of the city, on the subject
of the attempted invasion, had been great; and manifested
especially, within a few days, against Mr. Campbell, for sentiments
on the subject, exposed in a correspondence between him and the
Secretary of State, recently called for by Congress, printed in the
newspapers in the United States, and republished here. At one time
the consulate was believed to be in great danger of violence from
the mob; and the excitement is still far from being allayed. In view
of this representation we apprehended a long delay. The first
interview, however, between Commodore McKeever and the captain-
general, the Conde d’Alcoy, relieved us from all fear of this. Every
disposition was manifested to receive favorably the mission of the
Congress; and the belief is that the special matter of negotiation will
be speedily adjusted.
The commodore and suite were received, at the vice-regal palace, in
the most frank and cordial manner, and the personal relations of the
treating parties placed, at once, on a friendly footing. The governor-
general treated lightly the fear that had been suggested, of violence
to the consulate, avowing that all property and life in the city and
island were in the keeping of the government; and that safety in
both was more sure to none, than to the representatives and citizens
of the United States. Summoning the chief of police at once to his
presence, the following dialogue in substance took place between
them. “Have you heard, sir, of an apprehended attack by the
populace upon the American consulate?” “No, sir.” “Do you believe,
sir, that any such danger exists?” “No, sir.” “Could a project of the
kind be in agitation without your knowledge?” “No, sir.” “See to it,
sir,” added the count, with an intonation of voice not to be mistaken,
as he dismissed the functionary, “that nothing of the kind takes
place!”
The truth is, the warmth of sympathy felt by some of our fellow-
citizens for the would-be revolutionists within Cuba and the
marauding filibusters without, backed by visions of national and it
may be personal aggrandizement, through annexation, lead them to
magnify every grievance imaginary or real, and to fan into a flame
each spark of ill will elicited by the collisions that occur, in the hope
of embroiling our government with the crown of Spain; and, through
conflict and conquest, of making sure to us this choicest gem left in
her colonial tiara.
That the Cubans are most fearfully oppressed by the vice-regal
rulers here, and that the government under which they suffer is the
most rigorous military despotism in the civilized world, no one with
the slightest knowledge of the condition of the island can doubt. The
simple fact that twenty-four millions of dollars are annually wrung,
by various forms of taxation, from a white population of little more
than six hundred thousand, proves it, without an enumeration of the
different unjust monopolies, the prohibitory imposts upon the first
necessaries of life, the depreciating levies on all the products of
labor, and the vampire presence of a foreign soldiery, sufficient to
furnish a constant sentinel, it is said, to every four white men in the
country; or, a reference to the fact that there are no common
schools—no liberty of the press, no liberty of speech, and scarce the
liberty of thought. Still, sad as the truth of such a condition is, it
does not justify piratical invasion from without, or agitating and
revolutionizing influence on our part within.
The probability is that the stay of the Congress will be very brief;
and that, consequently, my personal knowledge of Havana and the
Habaneros will be limited to a hasty glance, through such loop-holes
of observation as I may accidentally light upon.
The beauty of the panorama from the anchorage is so varied and so
striking, that in the enjoyment of it, I have been satisfied thus far
without a visit to the shore, though this is the third day, including
the Sabbath, since our arrival. While examining closely with a glass
again and again, every feature of the open country to the east and
south, I could but indulge in many a reminiscence of tropical life at
the Sandwich Islands and South Seas, awakened by the plumed
palm and broad-leafed banana, the brightly gleaming hill sides and
velvet-like slopes characteristic of the scenery. On the opposite sides
of the harbor, the city and its fortresses,—its private dwellings and
public buildings, its towers and domes and embattled walls,—are
open to like inspection through the same medium, a sea-telescope
of surpassing excellence.
While in the midst of these observations this morning, screened from
the mid-day sun by the well-spread awnings of the poop-deck, my
attention was drawn to a movement near at hand on board,
occasioned by a succession of visits of ceremony from the “powers
that be” in this viceroyal dependency, to our commander-in-chief
and our captain. I am told, whether correctly or not, that the same
policy which of yore prevented Ferdinand and Isabella from keeping
faith with Columbus, in his appointment as viceroy of the New World
with undivided power, is still adhered to by the Spanish throne. The
supreme authority, in place of being vested in one representative of
the crown, is distributed among three—one at the head of the civil
affairs, another chief in those that are military, and a third supreme
in the control of the marine. Each is in his own department
independent of the other, and keeps check on his compeers in any
assumption of undue authority. The captain-general, however, has
precedence in matters of ceremony, and is the nominal head of the
government. He does not visit vessels of war, and the courtesy on
his part is expressed through an aide-de-camp. The visitor in his
stead on this occasion, was the Conde Villeneuva, a fine-looking
young man, in a richly embroidered dress of blue and silver, but
without military decorations. He had scarcely been ushered on the
deck, with the usual ceremony, when a barge, still more stately in
the number of its oarsmen and the dimensions of its banner of
“blood and gold,” than that by which he had arrived, was reported
by the quarter-master. This bore the Intendante, or Military Chief,
who crossed the gangway in full costume, with a magnificent star on
the breast and three or four crosses and badges of knighthood at
the button holes. Neither name nor title was announced with
sufficient distinctness to be heard, and in view of the number and
brilliancy of his decorations, I felt authorized in giving him
precedence of the count, by at least one grade in the peerage, and
set him down for a marquis: especially as the state in which the next
dignitary approached would lead to the supposition that he could be
nothing less than a duke—a grandee of the first rank. He came in a
superb sixteen-oared barge of the purest white, picked out in gold.
He was a most stately old gentleman, portly in person, fresh in
complexion for a Spaniard, and of the most courtier-like and finished
manners. Three magnificently jewelled stars decorated his left
breast, with the crosses of twice as many orders pendant beneath,
and over all the broad ribbon and insignia of the Golden Fleece. It
was the Commandant-general of Marine, or Naval Chieftain. These
visits of mere ceremony were brief, referring in conversation to the
most common-place topics, followed by a departure in the order of
arrival.
The weather since we have been here has been like that of the
finest days in June on the Hudson: the sun very hot, the sky
glowingly bright, the breeze fresh and seemingly pure, with heavy
showers occasionally in the afternoons. In the evenings and at night
the scene from shipboard is striking and impressive. Long lines of
brilliant gas-lights, marking the walls of the city abreast of us, with
the gleamings of others from fortress and tower reflected by the
glassy waters of the bay in streams of gold, and a glorious canopy of
sparkling stars above, compensate in a degree for the absence of
the moon; while a fine military band stationed on the ramparts
nearly opposite us discourses eloquently, till nine o’clock, the
compositions of the masters in opera.
July 8th.—My first visit on shore was in company with my messmate
F——, after the heat of the day had begun to pass. The low quays of
a yellowish stone which face the water, are thickly lined with the
smaller craft, engaged in the commerce of the port. We made our
way along these for some distance, through an atmosphere redolent
of tar and pitch and cordage—coffee and tobacco,—amid soldiers
and sailors and throngs of brawny negroes, more than half naked
and reeking with perspiration, in the labor of loading and unloading
cargoes. On turning into a narrow street leading into the city, we
soon discovered, that the buildings which from our moorings meet
the eye so strikingly in their gay tintings of sky-blue, pea-green,
peach-blossom, lemon and straw colors, with their mouldings,
cornices and balustrades of the purest white, are thickly interspersed
with others, dingy, shabby, decayed and dirty: barn-like, stable-like
and prison-like. To an untravelled visitor from the Northern States,
this last characteristic would be the first peculiarity in the aspect of
the houses to attract his attention. Every man’s dwelling here is
literally his castle, the defences of which give to its exterior, on the
ground floor especially, the appearance of a jail at home. The heavy
doors opening on the street, are of the most massive make, and
bossed and studded with iron so as to be bullet-proof, while the
lower windows are universally guarded from top to bottom by strong
bars and network of the same material. The general style of building
is the Spanish-Morescan, many of the dwellings being only one story
in height. The streets are straight and regular, but very narrow,
scarcely admitting two vehicles to pass each other, while the
sidewalks, as termed by us, are on a level with the way for
carriages, and a foot or eighteen inches only in width.
A short walk from the point at which we left the quay, brought us
upon a small but pretty and artistic square, called the Plaza de
Armas. It is enclosed with a handsome iron railing, is regularly laid
out in walks, bordered with gay flowers and shrubbery overhung by
the silvery trunks and long pendant branches of the palm-tree, and
ornamented in the centre with a fountain and statue of Ferdinand
VII. of Spain. Its southern side is faced in its whole length by the
palace of the governor-general, a spacious and handsome
quadrangular structure of stone, stuccoed and painted sky-blue, with
pilasters, cornice and balustrade around its flat roof, of white.
Our chief object in going on shore was the enjoyment of a drive
outside the walls. The vicinity of the Plaza furnished us with the
opportunity of a choice of equipage for the purpose. Lines and
groups of vehicles were standing along its sides and at the corners.
An omnibus of American fashion and manufacture was seen on its
route, and a carriage of modern style passing here and there, but
those on the stand were exclusively the common vehicle of the city
and country, the volante—a two-wheeled clumsy-looking machine of
by-gone times drawn on ordinary occasions by one horse. The body
is larger than that of an American gig or chaise, hung very low like
an old-fashioned phaeton, and so delicately poised on springs of
great elasticity as to sway about, under the slightest impulse, with a
most buoyant and luxurious motion.
I find even a pen-and-ink sketch so much more satisfactory than
verbal description, in conveying just ideas of novelties such as this,
that I am more than half disposed to attempt one here, at the
double hazard of defacing my paper and bringing in contempt my
skill in the arts. I will try it. The experiment is not quite so successful
and effective as I could wish it to be, but it will answer the purpose.
Do not think it, however, defective in the proportions exhibited,
either in regard to man and beast, or to the distance of both from
the body of the carriage. The wheels in their size and height, in
comparison with the top of the volante, the length of the shafts, and
the bulk of the black calesero, or postillion, in contrast with that of
the little pony he bestrides, are all true to the reality, rather
underdrawn than exaggerated. You must not suppose either that the
little horse is without a tail: for though not very distinctly visible in
the sketch, the tail is there; neatly plaited and closely twisted round
the hip, like the braid of a lady’s hair around her ear, and made fast
by a gay ribbon to the postillion’s saddle.
The colors of these carriages, in body, shafts and wheels, are more
varied than those of the rainbow: scarlet, yellow, blue, green—in
endless tintings, contrasting showily with mountings of silver or
silver-gilt, in greater or less profusion and massiveness, according to
the rank or riches of the owner. The harness to our eyes appears
complicated and heavy. It also is ornamented more or less
elaborately with silver or gilt platings. As to the postillion, picture to
yourself the most perfect personification of Congo blackness you
ever saw, in the form of a stout muscular negro, with features and
heels to match; put him in a very short-waisted jacket—scarlet, blue,
yellow or parti-colored, and gay with worsted lace for livery, and into
very high riding boots, large enough for Goliath, and with the sketch,
you will have a tolerable idea of the equipage in which F—— and I
set off from the Café Dominica, not far from the Plaza de Armas, for
a drive in the suburbs.
At the end of a half mile, it may be, through the narrow streets, with
shops and counting-rooms and dwellings on either side, widely open
and within reaching distance by the hand, we came to the principal
gateway in the western walls, leading directly upon the Paseo de
Isabella II., the fashionable promenade and drive without the walls:
the Hyde Park and Champs Elysee of the Habaneros. This extends
the whole length of the western side of the city, and is garden-like
and beautiful in its trees, shrubbery and flowers. Two broad carriage
ways run from end to end with four or more gravelled walks
between them; a fountain ornaments either extremity, and in the
centre is a statuette of Isabella II., erected shortly after her
succession when a child: the more welcome from associations of
purity and innocence, which an image of her majesty in later years
would be little calculated to suggest.
A range of stately buildings on the west, faces and overlooks this
point of aristocratic and fashionable reunion: an opera house and
palatial café with other imposing structures, giving quite a
metropolitan air to the scene. The first two mentioned bear the
name of Tacon, in honor of the captain-general of that name, during
whose rule they were built, and whose administration a few years
ago, was distinguished by such signal reforms in the police of the
city, and the entire suppression of the cut-throat outrages before so
common. The enlarged views, public spirit, energy and
determination which characterized his measures, stamped his name
indelibly on the city; and to these is the population indebted, not
only for the effectual suppression of crime, but for much also of the
ornamental architecture which it boasts.
South of the Paseo is the Champ de Mars, an extensive parade
ground, lined with spacious barracks and other governmental
buildings. Passing these we drove three or four miles over a broad
and well-kept macadamized avenue, filled with animated life in every
form, and lined with suburban residences luxuriant in the richness
and beauty of tropical growth in tree, shrub and flower: all in such
wide contrast with scenes witnessed in a drive of like length in the
suburbs of a city with us, as to excite the wonder, why more of our
citizens of wealth and leisure do not take the short trip to Havana in
the winter, to be amused and instructed by its novelties, and
charmed by the blandness of its climate and the splendor of its
vegetable life. Although the soil in this section of the island is of an
inferior quality to that of most other regions, there are evidences on
every hand of the richness and beauty which have secured to Cuba
the proud and winning title of “Queen of the Antilles,” and make her
the choicest colonial possession left to Spain.
From the heat of the climate, the construction of the houses, in
general, is such as to make them little more than so many open
pavilions, from which as you drive by, you unavoidably catch not
only the

“Manners living as they rise,”

but many, if not all, the habits of life of the inmates. The eye
penetrates at a glance, as it were, the entire domestic economy of
the household. The dwellings are, for the most part, one story only
in height, with a tower or mirador at one end or corner, for a “look-
out.” Externally they seem all door and window. These are very
wide, and extend from the ceiling to the floor, on a level with the
street. Thrown widely open in the cool of the day, the interior
becomes fully exposed: furniture and inmates—the whole family
group in full dress or dishabille as the case may be—a scene on the
stage of life, as open to inspection as one from a drama on the
boards of a theatre. This is as true of the dwellings of the rich as of
the poor. In seeing the whole diagram of the interior thus exposed
without any appearance of bed or bedroom, the wonder in my mind
was where the people could sleep? On expressing some curiosity on
this point, I was told that in many cases, the beds of the family
consist of mats or mattresses, spread at night on the floor, or in cots
in the reception-rooms, while in most houses an inner court is
encircled by small sleeping and dressing-rooms.
Many of the residences of the gentry and moneyed aristocracy in the
suburbs are luxurious and princely; exhibiting long suites of spacious
and elegantly furnished apartments, with floors of polished marble
and the oriental luxury of jetting fountains and clustering flowers,
endless in the variety of their tint and perfume. The gardens
attached to some of these are laid out with taste, and kept in the
nicest order, filled with an exuberance of choice plants known to us
at the North only in the dwarfish and stunted growth of the
conservatory. Indeed, many which are cherished exotics with us, are
here seen in rank profusion in the hedges and by the roadside, like
the thorn and the thistle of our ruder climate.
By the time of our return, the hour for the drive and promenade of
the citizens had arrived; and, as we approached the Paseo, we were
met and passed by great numbers of equipages of varied style.
Some were altogether American and European in their
appointments; but most were the native volante in greater or less
elegance and richness—some with one horse only, and others with
two. When two are used, the second is placed abreast of the one in
the shafts and ridden by the calesero. Each carriage contained from
one to three females, in full dress as if at a party—low necks and
very short sleeves: to which may be added, very fat figures and very
dark skins. Bonnets are not worn of course with this costume, nor
indeed with any other. The coiffure at this season is of ribbons,
gauzes, laces and other zephyr-like materials, with flowers and
jewelry; but, in the winter, I am told, these give place to head-
dresses of velvet and satin, with ostrich plumes, pearls and
diamonds. As the volantes pass and repass along the carriage drive,
salutations are exchanged between the ladies in the vehicles with
each other, and with acquaintances and friends among the
gentlemen on foot or on horseback, by the eyes, the fan and hat,
more than with the voice; but, so far as I observed, the ladies did
not alight as is the custom in Europe in many places of the kind, to
join in the promenade on foot, or form groups for conversation. At
nightfall there is a return to the city, where, for an hour or two, the
ladies amuse themselves in driving from shop to shop, to have such
articles as they ask for brought to their carriages for inspection, or,
proceeding to the Plaza de Armas, again join their associates of the
beau monde in display and flirtation by lamp-light or moonlight as
the case may be, while a regimental band in front of the
governmental palace gives a free concert of instrumental music till
nine o’clock. The evening on this occasion was delightful, and we
prolonged our stay and observations till that hour.
So well pleased was F—— as well as I with this first peep on shore,
that we repeated the visit two days after, driving as far as the
Bishop’s garden, the principal attraction of the kind in the
neighborhood of the city. Since then there has been much heavy
rain. The trade wind at the same time ceased, causing a closeness of
atmosphere that has been very oppressive, and made me more than
content to remain for the most part quietly on board ship: I say for
the most part, for I went once into the city, on a solitary pilgrimage
to the tomb of the good and great, and ever to be honored,
discoverer of the New World. As you know, his remains were
removed at intervals of time of various length, from Valladolid where
he died, to Seville, and from Seville to St. Domingo, the resting-place
designated for them in his will. On the cession of that island to
France in 1796, they were brought to Cuba, and deposited with
great ceremony in the cathedral of Havana. A medallion likeness in
marble, with a short inscription on a mural tablet, marks the spot in
the chancel near the high altar where they have found, as it is to be
hoped, a lasting sepulchre. No American can stand near them
unmoved: or without a recurrence in thought to the sublime vision of
an unknown world, which so long filled the mind, and amid endless
discouragements and disappointments sustained the hopes and
energies of the adventurous navigator, till it issued in a glorious
reality; or without deep sympathy in the vicissitudes and trials of his
after life, and the neglect and injustice which brought his gray hairs
with sorrow to the tomb. Near by are exhibited—I was about to say
the ignominious, but I recall the epithet—the ennobled fetters with
which an ungrateful monarch permitted a jealous rival and enemy to
manacle his limbs.
On another occasion I left the ship after night, for a row across the
harbor with Lieut. T—— in his gig. It had been our intention to pass
the evening in the city, in a visit to some families of his acquaintance
to whom he wished to introduce me, but the heat and dampness of
a debilitating and sickening atmosphere during the day, determined
us to postpone this till the return of a more invigorating and elastic
air. Our row was from the anchorage of the men-of-war through that
of the merchant ships, at another point in the harbor, to a landing
near the town of Regla opposite the city; a place of no enviable
notoriety, in times past, as a kind of city of refuge through the
indulgent winkings of government officials, first for the pirates who
once infested these regions, and more recently for dealers in the
slave trade. Here also is one of the principal amphitheatres for the
exhibition of the favorite national amusement, the bull fight. The
special object of the trip, on the part of my companion, had some
reference to the disposition of the slush of the Congress, if you can
comprehend the import of so elegant a term in a ship’s economy:
mine partly the pleasure of his company, and partly to inquire the
state of the sick in a private hospital for cases of yellow fever, and to
learn the practicability of visiting any American seamen, who might
be suffering there from this pest of Havana, already beginning its
annual ravages.
The night was very dark for a tropical region, and the most striking
imagery discernible, as we threaded our way amidst the shipping,
was the black masses of spars and rigging pencilled against the sky
above us; the long line of brilliant lights marking the walls of the city
reflected in streams of fire on the glassy water; and the alternate
dim glimmerings and blinding flashes of the revolving pharos,
surmounting the lofty tower of the Moro.
July 10th.—Bright weather has returned, and with it the regular
trade wind from the sea. We rejoice in this, not only from the
greater comfort it insures, but also from the promise it holds out of
continued health in our ship’s company. The change induced Lieut. T
—— and myself to make our contemplated visit on shore last
evening. For a couple of hours before nightfall, we drove in a volante
a circuit of some miles through the environs, amid scenes and
scenery of unceasing novelty and endless variety, embracing the
attractive and beautiful; the grotesque and ludicrous; elegance and
magnificence, filth, nakedness and degradation, strangely
commingled. Here, a splendid equipage as perfect in its
appointments as any to be met in New York or London; there, a
vehicle as rude and clumsy as if belonging to the birthday of
invention. Here a caballero admirably mounted, riding a blooded
horse with all the stately solemnity of a grandee of the first order;
there, a negro or montero, in rags and half nakedness urging
onward, at a most sorry pace, as broken down a skeleton of a pony
or jackass as ever contrived to put one foot before another. Here a
squad of well-equipped soldiers; there a gang of manacled and
ruffian-looking galley-slaves—thus without end, exciting alternate
admiration and disgust, smiles and pity. Before commencing the
visits of the evening, we took a bird’s-eye view of the fashionable
movements in the Paseo, from the upper balconies of the Café Tacon
which overlook it, and of the magnificent panorama of the city, the
surrounding country, and the sea, commanded from the leads of its
flat roof, and then proceeded to meet an engagement at the
consulate for tea.
July 11th.—It has been known for two or three days past, that the
object of our visit was well nigh accomplished, and that the
prisoners of Contoy were to be delivered to the keeping of our flag,
on the condition of their immediate transportation to the United
States. The U. S. steamer Vixen came into port yesterday, bringing
Commodore Morris as an additional agent of our government in the
negotiation of this matter, but too late for the object of his mission,
the work being already done.
At twelve o’clock this morning, the prisoners were brought on board
the Congress in the boats of the Spanish ship-of-the-line near us.
They are some forty-two or three in number, appearing a sorry-
looking set of adventurers indeed, as they crossed the ship’s sides to
be mustered in the gangways, and turned over to our charge by the
Spanish officer bringing them. Most of them are young—many mere
boys—and a majority evidently scapegraces, including a few wild-
looking, muscular and wiry Western men, tall Kentuckians and
Mississippi black-legs. They have been well fed and well taken care
of, it is said; but they all looked pale, and some seemed nervously
agitated. This is to be attributed, it is probable, to the uncertainty till
the very moment, of the result of the sudden summons they had
received from their keepers to prepare for some event of which they
were kept ignorant, and which they had more reason to fear might
be death under the fire of a platoon of soldiers, than liberty beneath
the flag of their country. During their captivity they had been denied
all intercourse with others, and had no means of learning their
probable fate. At times, the most intelligent among them had been
subject to threats of immediate execution, seemingly in the hope of
extorting some confession differing from the general attestation, that
they had been entrapped into the expedition, under a contract of
being conveyed to the isthmus, on their way to California, and on
discovering the imposition had refused to take part in the attempted
invasion. The most cheering hopes that had reached them were
derived from the salutes, in honor of the 4th of July. They inferred
from these the presence of American men-of-war of heavy metal,
and that their case was neither forgotten nor neglected by the
American government. I well recollect thinking and feeling, at the
time, that the repeated thunder of the heavy batteries of the
Congress, from sunrise to sunset on that day, re-echoed by all the
men-of-war in port, must have brought them hope with no uncertain
sound, whether it reached their ears in the hold of the guard-ship or
the dungeons of the Moro castle: for even the place of their
confinement was withheld from us. At three o’clock this afternoon,
the whole number was transferred to the sloop-of-war Albany, for
passage to Pensacola. She is to sail to-morrow morning at daybreak,
and it is announced that the Congress will leave the harbor in
company with her, and proceed to her destination on the coast of
Brazil.
Great credit is due to Commodore McKeever for the speedy
adjustment of this difficulty. His courteousness and amenity at once
made smooth the way to negotiation. He is a man of peacefulness
and good will, more disposed to pour the oil of kindness on troubled
waters than to cast in any new element of agitation, and to his
firmness and gentleness combined, are to be attributed the early
and desirable result attained.
Thus terminates this filibustering invasion of Cuba. But is it the end?
The enterprise, as projected and fitted out, was most ill-judged and
piratical. But is it true that its origin and means of equipment were
entirely from abroad? Is there no deep sympathy with such an
adventure among the Creole inhabitants of the island themselves? Is
the spirit of patriotism and of liberty here dead? Are there no
groanings beneath the galling chains of a cruel and grinding
despotism? No sense of degradation, no purpose to be free, among
the intelligent and aspiring of the native population? It is impossible
that there should not be. The prosperity and the glory of the
unfettered nation immediately facing them are too near, and too
brilliant, not to be reflected eventually in attractive splendor, through
every valley, and over every mountain top of this gem of the seas.
An atmosphere of freedom so near, must impart something of its
elasticity and its power even to the depressing vapors of such a
despotism. The Cuban in his summer visits of business or of
pleasure to the United States, inhales and carries it back with him,
and the American in his winter sojourn here, insensibly bears it
wherever he goes. The breath of liberty has been, and will continue
to be inspired by the natives of the island; and unless the mother
country, with timely wisdom, changes her colonial policy and
ameliorates her iron rule, restlessness, agitation and revolt, must be
the issue, and Cuba become independent in self-rule, or free by
voluntary annexation to the nation to which, geographically at least,
she rightfully belongs.
CHAPTER IV.

Gulf of Florida.

July 12th.—True to the announcement last night, all hands were


called to weigh anchor at daybreak this morning; and, by sunrise,
under the double impulse of a light land breeze, and the oars of a
long line of man-of-war boats having the Congress in tow, we made
our way, through the narrow entrance of the port, to the open sea.
Many merchant ships also were taking their departure. The shrill
calls of the bugle from barrack and fortress; the unfurling of signal
and banner from mast-head, battlement and tower; strains of
military music from different points; the lively movement in all
directions of boats and small craft on the water; and the rising hum
of active life from the city, gave exciting animation to the picture,
while the purple hues of the morning and its balmy breath, added a
fresh charm to the whole.
After enjoying the scene till we were outside the harbor, I went
below, intending to return to the deck in time for a farewell view, not
only of the island, but of the Moro castle and city also. So rapid was
our course, however, from a strong current, as well as a fresh
breeze, that, on reaching the poop for this purpose, “the blue above
and the blue below” were alone to be seen; and undisguised
satisfaction was every where manifested that, not only the sickly,
though beautiful port, but the entire island had been left out of sight
behind us.
The first object that met my eyes this evening, at the close of our
accustomed worship on deck, was the silver crescent of a new moon
beautifully defined in the empurpled sky; and, I interpreted the mild
and benignant beamings sent down upon us, from its young course,
as an omen of good in our voyage across the wide sea.
July 22d, N. Lat. 37°, W. Long. 59°.—We made our way gently and
pleasantly through the Straits of Florida: sighting, during successive
nights, on either sides of the channel, while making long stretches
against a head wind, the lights of Key West and Sand Key, Carysfort
Reef, and Gun Key. These numerous beacons speak the perilous
navigation of the region. It is peculiarly the empire of the wreckers,
whose lives are spent in constant search along the reefs, which for
two hundred miles here edge the coast, for the vessels which in
great numbers are yearly cast upon them by storms, or the
treacherous currents of a calm. The value of the commerce which
annually passes through the Gulf of Florida is estimated at four
hundred millions of dollars, of which not less than half a million,
each year, is lost by shipwreck, notwithstanding the vigilance and
prompt exertion of the amphibious and heroic race, whose business
is the rescue of the lives and property here endangered.
For three days after regaining a latitude which admitted of plain
sailing, we had boisterous weather and a wild sea, but an unclouded
sky. The elastic and invigorating atmosphere attending it, was most
welcome after the heats of Cuba. At such times the ocean, in its
ever-varying forms of beauty and changing shades of prismatic light
in the sunshine, often outrivals in attractiveness the still life of a
wide-spread landscape on shore. There is, too, a voice of music
breathing over it; for, not less truthfully than poetically, has it been
said of the ocean, there is
“In its sleep a melody,
And in its march a psalm.”

Now, however, in place of the

“Restless, seething, stormy sea,”


we have on every side an illimitable plain of the deepest blue, with
scarce a perception of those giant heavings from beneath, which
ever, in a greater or less degree, tell of an unfathomable abyss of
waters. Over this we are hurried, without a consciousness of motion,
at the rate of ten miles the hour, by a breeze as balmy, if not as
fragrant, as the zephyrs of “Araby the blest.” Add to these
surroundings, the moon, at night, riding the heavens above in
sublime tranquillity, and you will not be surprised, if, at times at
least, I am ready with the poet to exclaim—
“Oh! what pleasant visions haunt me,
As I gaze upon the sea,
All the old romantic legends—
All my dreams come back to me!”

July 29th.—Happily I am not unfitted for mental occupation; by


being on shipboard, as is the case with many, and, with the prospect
of a voyage of fifty or sixty days, I have set myself closely to work.
The early part of the day I give to the graver studies of my
profession, and the later to lighter reading; visits to the sick, when
there are such; exercise on deck with some fellow-officer; and such
“walks of usefulness” as I can light upon among the crew, in
different parts of the ship in the evening, fill up the intervals of
leisure till bed-time.
One of our young officers, Midshipman L——, has the misfortune to
be incapacitated for duty, by a nervous affection of the eyes and
head, the consequence of three separate attacks of fever in the Gulf
of Mexico. The surgeons interdict to him all use of the eyes; and, to
relieve the ennui into which he is thus thrown, I have invited him to
my room for an hour or two every day, that by my reading aloud he
may have the benefit of such works as I am running over; travels
and biography—Maxwell’s Russia, Irving’s Mahomet, and the
excellent books of Miss McIntosh, the accomplished sister of the
captain of the Congress, interspersed with those of a more serious
character, such as Angell James’ “Young Man from Home” and Pike’s
“Persuasives to Early Piety”—have thus far occupied these hours.
The touches of deep feeling frequently met in the writings of Miss
McIntosh, in her lifelike and instructive delineations of character,
have been the means of bringing into exercise sympathies, the
involuntary betrayal of which to each other, has led to quite an
intimate friendship, considering the disparity of our years.
For a week after leaving port, we had every reason to hope that it
had been with entire impunity, in regard to health, that we had been
exposed to the burning sun, and, at this season of the year,
pestilential air of Havana. But on the eighth day, just as we were
congratulating ourselves on the certainty of our escape from all
infection, a light fever made its appearance among both officers and
men. Some dozen in number were brought down by it. It was the
yellow fever, but of so modified a type, that, in a few days, all were
convalescent and no new cases occurred.
Sickness, whether of a serious nature or not, presents an
opportunity of approach, and often gives access to the confidence
which I am careful to improve. I was much interested, a day or two
ago, in an interview with a fine-looking young man of the crew,
under the influence of the prevailing epidemic. He had evidently
been familiar with better associations than those of a man-of-war;
and, I soon learned from him that he was the prodigal son of a pious
mother, by whom he had been carefully trained and cherished, and
was a child of many prayers. The first glance of his eye, as I
approached his cot, told me by the starting tears—not from alarm,
for no danger was apprehended in his case, but from remembrances
of the past—that he was in a state of mind to open his heart to me;
and, in the admissions and confessions of a long conversation, I
became deeply interested in the penitence and purposes of future
well-doing which he avowed.
In a hammock near by I found a middle-aged Scotchman, of
intelligent and respectable appearance, who was equally open to
religious conversation. He told me he had been long deeply sensible
of his guilt and misery as a sinner, and greatly troubled in mind and
conscience; that a conflict had been going on in his soul, as if a
good and an evil spirit were ever in contest there for the mastery
over him: but that the good at last had gained the triumph, and he
was “at peace with the Father, through the Son and Spirit, and
feared no evil—not death itself.”
August 7th, N. Lat. 12°, W. Long. 38°.—Delicious seems the only
epithet descriptive of the atmosphere we are now breathing, and
“delicious—delicious!” is the stereotyped exclamation of every one,
as he mounts to the deck from below and drinks in the pure ether,
as if it were the very elixir of life. The morning is in all respects
lovely. The heavens have a look of infinity. A snow-white cloud alone
floats here and there in them; and, as, rushing over the blue sea,
before the fresh trade-wind, we dash the foam widely from our
prow, unnumbered flying fish spring into the air, and skim the
surface of the water before and around us, like so many birds of
silver gleaming brightly in the sun.
August 28th, N. lat. 3° 30′, W. Long. 25°.—The region, through
which we have been making our way, for the last ten days, is known
among seamen by the very unsentimental name of the “doldrums.”
The origin of the epithet it might be difficult to trace. It is an
equatorial belt, characterized by light weather and head-winds; by
alternate calms and squalls, clouds and rain. Hence every thing on
board and without, is, and has been, in as wide contrast as possible
with that of my last date. The whole ship is saturated, both on deck
and below, with rain, and the washings of the sea through the ports
and hawser-holes. The air on deck is close and oppressive, and
below stifling and musty, and the tossings and pitchings and rolling
of the ship any thing but agreeable to the fastidious stomachs of
many on board—especially to my friend T——, who, though familiar
for more than twenty years with the caprices of the deep, is in a
most annoying state of discomfort at every return of rough weather.
The progress made on our course is small, averaging not more than
twenty-five or thirty miles in the twenty-four hours, though we sail
by tacks in that period, from a hundred to a hundred and fifty. We
are navigating by Lieut. Maury’s wind and current charts, and
notwithstanding the seeming tedium of our progress, in beating
against what he denominates the south-west monsoons of these
latitudes, are satisfactorily demonstrating the truth of his theory and
the correctness of his sailing directions in conformity with it.
It is now some six or eight years since this distinguished young
officer, whose attainments in abstruse and practical science have
reflected such high honor not only on his profession but on his
country, conceived the idea of collecting as many of the log-books of
navigators as could be secured, with a view of collating them, and of
projecting upon charts, to aid in the better navigation of the sea, the
general experience in winds and currents, at all periods of the year,
in the different regions of the ocean. He at the same time urged
upon the masters of ships, the importance of adding to the usual
subject-matter of their logs, the temperature of the water, the set of
currents, and the depth of the bed of the ocean when it was
practicable to obtain soundings. As an incentive to the trouble of
thus keeping a log, and of furnishing an abstract of it to the National
Observatory at Washington, the promise was given that each
shipmaster complying with the suggestion, should receive
gratuitously from the government, a copy of the charts and sailing
directions which might be the result.
Not fully alive to the object or aware of its great importance, the
response was slow and imperfect. In the course of a few years,
however, sufficient data were secured; and the first practical result
was the shortening by ten days of the voyage to the equator, and
consequently to Rio de Janeiro. From the earliest times this passage,
from North America, had been made by running obliquely across the
Atlantic to the longitude of the Cape de Verde Islands, before
venturing to strike the north-east trade-wind. A traditionary report
and belief in the existence of strong adverse currents along the
South American coast, and the fear of not being able to double Cape
St. Roque, should the equator not be crossed far to the East, led to
this. It required no little moral courage and determination in one of a
class proverbially wedded to custom and subject to superstition, to
venture the trial of the new route. Such an one was found, however,
and the result was most satisfactory. The opinion is now firmly
entertained by many of the most experienced navigators, that by
following the direction of the wind and current charts, the length of
the voyage is diminished one fifth. This is an immense saving of time
in a commercial point of view. Doubtless the patient perseverance of
the accomplished astronomer, in this new field of discovery, with the
aids which are now rapidly placed in his possession, will lead to
similar results on all the grand routes of navigation over every
ocean, and place the commercial world in indebtedness to his genius
for savings in time, and consequently in money, of incalculable
amounts.
Last night, from nine till ten o’clock, we enjoyed a beautiful
spectacle, in a halo around the moon of colors as vivid as those of
an ordinary rainbow, and in concentric circles most clearly defined.
The moon, near the full, retained her face of silver in the midst of a
field of gold, shadowing towards the outer edge into a delicate
amber and then into the deepest maroon. A belt of the purest blue
intervened, when the encircling colors were repeated in fainter hues;
apparently, though not philosophically, a reflection of the first. The
phenomenon was so striking, and so singularly beautiful, that Lieut.
R——, the officer of the deck at the time—one ever alive to the
poetic and impressive in nature, as well as to the scientific and
practical in his profession—dispatched a messenger hurriedly for me.
The commodore and captain were also summoned, and soon, with
most of the other officers, joined us on the poop, while the whole
crew, from different parts of the ship, shared in the admiration
excited by the scene. It is the first exhibition of any thing unusual in
sky or sea that has thus far marked our passage. A humid
atmosphere and a thin fleecy scud were its accompaniments.
August 23d.—In the course of the night of the 22d inst. we took the
south-east trade-wind, three degrees north of the equator, and at
once bade adieu to the doldrums. We crossed the line at high noon,
yesterday, on the parallel of 28° 30′ W. long, without any very
perceptible ‘jolt;’ and are rushing on our course at the rate of ten
miles the hour.

You might also like