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