JavaScript Absolute Beginner's Guide

Transcription

JavaScriptKirupa ChinnathambiPearson Education800 East 96th StreetIndianapolis, Indiana 46240USA

JavaScript Absolute Beginner’s GuideCopyright 2017 by Pearson EducationAll rights reserved. No part of this book shall be reproduced, stored ina retrieval system, or transmitted by any means, electronic, mechanical,photocopying, recording, or otherwise, without written permission fromthe publisher. No patent liability is assumed with respect to the use ofthe information contained herein. Although every precaution has beentaken in the preparation of this book, the publisher and author assume noresponsibility for errors or omissions. Nor is any liability assumed for damagesresulting from the use of the information contained herein.ISBN-13: 978-0-7897-5806-4ISBN-10: 0-7897-5806-7Library of Congress Control Number: 2016939721Printed in the United States of AmericaFirst Printing: July 2016TrademarksAll terms mentioned in this book that are known to be trademarks orservice marks have been appropriately capitalized. Pearson cannot attest tothe accuracy of this information. Use of a term in this book should not beregarded as affecting the validity of any trademark or service mark.Warning and DisclaimerEvery effort has been made to make this book as complete and as accurateas possible, but no warranty or fitness is implied. The information providedis on an “as is” basis. The author and the publisher shall have neither liabilitynor responsibility to any person or entity with respect to any loss or damagesarising from the information contained in this book.Special SalesFor information about buying this title in bulk quantities, or for special salesopportunities (which may include electronic versions; custom cover designs;and content particular to your business, training goals, marketing focus,or branding interests), please contact our corporate sales department atcorpsales@pearsoned.com or (800) 382-3419.For government sales inquiries, please contactgovernmentsales@pearsoned.com.For questions about sales outside the U.S., please contactintlcs@pearsoned.com.Acquisitions EditorMark TaberDevelopment EditorChris ZahnCopy EditorAutumn SpaldingProduction EditorLori LyonsTechnical EditorsTrevor McCauleyKyle Murray

This page intentionally left blank

Contents at a GlanceIntroduction . 11Part IHello, World!. 5The Basic Stuff2Values and Variables . 133Functions . 194Conditional Statements: If, Else, and Switch . 315Meet the Loops: For, While, and Do While! . 476Timers . 597Variable Scope. 678Closures . 779Where Should Your Code Live? . 8910Commenting Your Code .101Part IIIt’s an Object-Oriented World11Of Pizza, Types, Primitives, and Objects .10912Strings.12113When Primitives Behave Like Objects .13314Arrays.13915Numbers.14916A Deeper Look at Objects .16117Extending Built-in Objects .17918Booleans and the Stricter and ! Operators .18919Null and Undefined.19520Immediately Invoked Function Expressions .201Part IIIWorking with the DOM21JS, The Browser, and The DOM .21922Finding Elements in the DOM .23123Modifying DOM Elements .23724Styling Your Content .24725Traversing the DOM.25526Creating and Removing DOM Elements .26527In-Browser Developer Tools .279

viPart IVDealing with Events28Events .29929Event Bubbling and Capturing .31130Mouse Events .32531Keyboard Events .33932Page Load Events and Other Stuff.34933Handling Events for Multiple Elements .36334Conclusion .373Glossary . 377Index. 381

viiTable of ContentsIntroduction. 1Parlez-vous JavaScript? . 2Contacting Me/Getting Help . 41Hello, World! . 5What Is JavaScript? . 7A Simple Example . 8Code Editing Tools. 8The HTML Document . 9Looking at the Code: Statements and Functions . 10IThe Basic Stuff2Values and Variables.13Using Variables . 14More Variable Stuff . 15Naming Variables . 15More on Declaring and Initializing Variables . 163Functions .19What Is a Function? . 22A Simple Function . 22Creating a Function That Takes Arguments . 24Creating a Function That Returns Data. 27The Return Keyword . 27Exiting the Function Early. 284Conditional Statements: If, Else, and Switch .31The If/Else Statement . 32Meet the Conditional Operators . 34Creating More Complex Expressions. 36Variations on the If/Else Statement . 38Phew . 39

viiiSwitch Statements . 39Using a Switch Statement. 39Similarity to an If/Else Statement . 42Deciding Which to Use . 445Meet the Loops: For, While, and Do While!.47The for Loop . 49The Starting Condition . 51Terminating Condition (aka Are we done yet?) . 51Reaching the End . 51Putting It All Together. 52Some for Loop Examples . 52Stopping a Loop Early . 53Skipping an Iteration . 53Going Backwards. 54You Don’t Have to Use Numbers . 54Array! Array! Array! . 54Oh No He Didn’t! . 55The Other Loops . 55The while Loop . 56The do.while Loop . 566Timers .59Meet the Three Timers . 60Delaying with setTimeout . 60Looping with setInterval . 61Animating Smoothly with requestAnimationFrame. 627Variable Scope .67Global Scope . 68Local Scope . 70Miscellaneous Scoping Shenanigans . 71Declarations Using var Do Not Support Block Scoping. 71How JavaScript Processes Variables . 72Closures . 748Closures .77Functions within Functions . 78When the Inner Functions Aren’t Self-Contained . 81

ix9Where Should Your Code Live?.89The Options on the Table. 90Approach #1: All the Code Lives in Your HTML Document . 92Approach #2: The Code Lives in a Separate File . 93The JavaScript File . 93Referencing the JavaScript File . 94So.Which Approach to Use? . 97Yes, My Code Will Be Used on Multiple Documents! . 97No, My Code Is Used Only Once, on a Single HTML Document! . 9910 Commenting Your Code . 101What Are Comments? .102Single Line Comments .103Multi-line Comments.104Commenting Best Practices .106IIIt’s an Object-Oriented World11 Of Pizza, Types, Primitives, and Objects . 109Let’s First Talk About Pizza.110From Pizza to JavaScript .113What Are Objects? .115The Predefined Objects Roaming Around .11712 Strings . 121The Basics.122String Properties and Methods .124Accessing Individual Characters .124Combining (aka Concatenating) Strings .125Making Substrings out of Strings .126Splitting a String/split .128Finding Something Inside a String .129Upper and Lower Casing Strings .130

x13 When Primitives Behave Like Objects . 133Strings Aren’t the Only Problem .134Let’s Pick on Strings Anyway .134Why This Matters .13714 Arrays . 139Creating an Array .140Accessing Array Values .141Adding Items to Your Array .143Removing Items from the Array .145Finding Items in the Array .146Merging Arrays .14715 Numbers . 149Using a Number.150Operators .151Doing Simple Math .151Incrementing and Decrementing .152Special Values—Infinity and NaN .153Infinity .153NaN.154The Math Object .154The Constants .155Rounding Numbers .157Trigonometric Functions .158Powers and Square Roots.158Getting the Absolute Value .159Random Numbers .15916 A Deeper Look at Objects . 161Meet the Object .162Creating Objects .163Specifying Properties .167Creating Custom Objects .169The this Keyword.175

xi17 Extending Built-in Objects . 179Say Hello to Prototype.Again—Sort of! .181Extending Built-in Objects Is Controversial .185You Don’t Control the Built-in Object’s Future .186Some Functionality Should Not Be Extended or Overridden .18618 Booleans and the Stricter and ! Operators. 189The Boolean Object .190The Boolean Function .190Strict Equality and Inequality Operators .19219 Null and Undefined . 195Null .196Undefined .19720 Immediately Invoked Function Expressions . 201Writing a Simple IIFE.203Writing an IIFE That Takes Arguments .204When to Use an IIFE .205Avoiding Code Collisions .206Closures and Locking in State.207Making Things Private.213IIIWorking with the DOM21 JS, The Browser, and The DOM . 219What HTML, CSS, and JavaScript Do .220HTML Defines the Structure .220Prettify My World, CSS! .222It’s JavaScript Time! .223Meet the Document Object Model .225The Window Object .227The Document Object .228

xii22 Finding Elements in the DOM . 231Meet the querySelector Family.232querySelector.233querySelectorAll .233It Really Is the CSS Selector Syntax .23423 Modifying DOM Elements . 237DOM Elements Are Objects—Sort of! .238Let’s Actually Modify DOM Elements.240Changing an Element’s Text Value .242Attribute Values .24224 Styling Your Content . 247Why Would You Set Styles Using JavaScript? .248A Tale of Two Styling Approaches .248Setting the Style Directly .249Adding and Removing Classes Using classList .250Adding Class Values.250Removing Class Values .251Toggling Class Values .251Checking Whether a Class Value Exists .252Going Further .25225 Traversing the DOM . 255Finding Your Way Around.256Dealing with Siblings and Parents .259Let’s Have Some Kids!.259Putting It All Together .261Checking Whether a Child Exists .261Accessing All the Child Elements .261Walking the DOM.26226 Creating and Removing DOM Elements . 265Creating Elements .266Removing Elements .271Cloning Elements .273

xiii27 In-Browser Developer Tools . 279Meet the Developer Tools .280Inspecting the DOM .282Debugging JavaScript .287Meet the Console.293Inspecting Objects .294Logging Messages .296IV Dealing with Events28 Events . 299What Are Events? .300Events and JavaScript .3021. Listening for Events .3022. Reacting to Events .304A Simple Example .305The Event Arguments and the Event Type .30729 Event Bubbling and Capturing . 311Event Goes Down. Event Goes Up. .312Meet the Phases .316Who Cares? .319Event, Interrupted .31930 Mouse Events . 325Meet the Mouse Events .326Clicking Once and Clicking Twice .326Mousing Over and Mousing Out.328The Very Click-like Mousing Down and Mousing Up Events .330The Event Heard Again and Again and Again! .331The Context Menu .332The MouseEvent Properties .333The Global Mouse Position .333The Mouse Position Inside the Browser .334Detecting Which Button Was Clicked .335Dealing with the Mouse Wheel .336

xiv31 Keyboard Events . 339Meet the Keyboard Events .340Using These Event

xv Dedication To Meena! (Who still laughs at the jokes found in these pages despite having read them a bazi