THIRD EDITION JavaScript Pocket Reference David Flanagan Beijing • Cambridge • Farnham • Köln • Sebastopol • Tokyo JavaScript Pocket Reference, Third Edition by David Flanagan Copyright © 2012 David Flanagan. All rights reserved. Printed in the United States of America. Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472. O’Reilly books may be purchased for educational, business, or sales promo- tional use. Online editions are also available for most titles (http://my.safari booksonline.com). For more information, contact our corporate/institutional sales department: (800) 998-9938 or [email protected]. Editor: Simon St. Laurent Production Editor: Teresa Elsey Proofreader: Kiel Van Horn Indexer: Jay Marchand Cover Designer: Karen Montgomery Interior Designer: David Futato Illustrator: Robert Romano October 1998: First Edition. November 2002: Second Edition. April 2012: Third Edition. Revision History for the Third Edition: 2012-04-06 First release See http://oreilly.com/catalog/errata.csp?isbn=9781449316853 for release de- tails. Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are registered trademarks of O’Reilly Media, Inc. JavaScript Pocket Reference, the image of a Javan rhinoceros, and related trade dress are trademarks of O’Reilly Media, Inc. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and O’Reilly Media, Inc., was aware of a trademark claim, the designations have been printed in caps or initial caps. While every precaution has been taken in the preparation of this book, the publisher and authors assume no responsibility for errors or omissions, or for damages resulting from the use of the information contained herein. ISBN: 978-1-449-31685-3 [M] 1333663134 Contents Preface vii Chapter 1: Lexical Structure 1 Comments 1 Identifiers and Reserved Words 2 Optional Semicolons 3 Chapter 2: Types, Values, and Variables 5 Numbers 6 Text 9 Boolean Values 12 null and undefined 13 The Global Object 14 Type Conversions 15 Variable Declaration 19 Chapter 3: Expressions and Operators 23 Expressions 24 Operators 28 Arithmetic Operators 32 Relational Operators 36 Logical Expressions 39 iii Assignment Expressions 42 Evaluation Expressions 43 Miscellaneous Operators 44 Chapter 4: Statements 49 Expression Statements 51 Compound and Empty Statements 52 Declaration Statements 53 Conditionals 55 Loops 59 Jumps 64 Miscellaneous Statements 70 Chapter 5: Objects 75 Creating Objects 76 Properties 79 Object Attributes 90 Chapter 6: Arrays 93 Creating Arrays 94 Array Elements and Length 95 Iterating Arrays 96 Multidimensional Arrays 97 Array Methods 98 ECMAScript 5 Array Methods 103 Array Type 107 Array-Like Objects 107 Strings as Arrays 108 Chapter 7: Functions 111 Defining Functions 112 Invoking Functions 115 iv | Table of Contents Function Arguments and Parameters 121 Functions as Namespaces 124 Closures 125 Function Properties, Methods, and Constructor 129 Chapter 8: Classes 133 Classes and Prototypes 134 Classes and Constructors 136 Java-Style Classes in JavaScript 141 Immutable Classes 143 Subclasses 144 Augmenting Classes 146 Chapter 9: Regular Expressions 149 Describing Patterns with Regular Expressions 149 Matching Patterns with Regular Expressions 158 Chapter 10: Client-Side JavaScript 163 Embedding JavaScript in HTML 163 Event-Driven Programming 165 The Window Object 165 Chapter 11: Scripting Documents 179 Overview of the DOM 179 Selecting Document Elements 182 Document Structure and Traversal 188 Attributes 190 Element Content 192 Creating, Inserting, and Deleting Nodes 195 Element Style 197 Geometry and Scrolling 201 Table of Contents | v Chapter 12: Handling Events 205 Types of Events 207 Registering Event Handlers 215 Event Handler Invocation 218 Chapter 13: Networking 225 Using XMLHttpRequest 225 HTTP by <script>: JSONP 233 Server-Sent Events 236 WebSockets 237 Chapter 14: Client-Side Storage 239 localStorage and sessionStorage 240 Cookies 245 Index 251 vi | Table of Contents Preface JavaScript is the programming language of the Web. The over- whelming majority of modern websites use JavaScript, and all modern web browsers—on desktops, game consoles, tablets, and smartphones—include JavaScript interpreters, making JavaScript the most ubiquitous programming language in his- tory. JavaScript is part of the triad of technologies that all Web developers must learn: HTML to specify the content of web pages, CSS to specify the presentation of those pages, and JavaScript to specify their behavior. Recently, with the advent of Node (http://nodejs.org), JavaScript has also become an im- portant programming language for web servers. This book is an excerpt from the more comprehensive Java- Script: The Definitive Guide. No material from the out-of-date second edition remains. I’m hopeful that some readers will find this shorter and denser book more useful than the larger and more intimidating volume from which it came. This pocket reference follows the same basic outline as the larger book: Chapters 1 through 9 cover the core JavaScript language, start- ing with fundamental matters of language syntax—types, val- ues, variables, operators, statements—and moving on to cov- erage of JavaScript objects, arrays, functions and classes. These chapters cover the language itself, and are equally relevant to programmers who will use JavaScript in web browsers and programmers who will be using Node on the server-side. vii To be useful, every language must have a platform or standard library of functions for performing things like basic input and output. The core JavaScript language defines a minimal API for working with text, arrays, dates, and regular expressions but does not include any input or output functionality. Input and output (as well as more sophisticated features, such as net- working, storage, and graphics) are the responsibility of the “host environment” within which JavaScript is embedded. The most common host environment is a web browser. Chapters 1 through 9 cover the language’s minimal built-in API. Chap- ters 10 through 14 cover the web browser host environment and explain how to use “client-side JavaScript” to create dy- namic web pages and web applications. The number of JavaScript APIs implemented by web browsers has grown explosively in recent years, and it is not possible to cover them all in a book of this size. Chapters 10 through 14 cover the most important and fundamental parts of client-side JavaScript: windows, documents, elements, styles, events, net- working and storage. Once you master these, it is easy to pick up additional client-side APIs, which you can read about in JavaScript: The Definitive Guide. (Or in Canvas Pocket Refer- ence and jQuery Pocket Reference, which are also excerpts from The Definitive Guide.) Although the Node programming environment is becoming more and more important, there is simply not room in this pocket reference to include any information about server-side JavaScript. You can learn more at http://nodejs.org. Similarly, there is no room in the book for an API reference section. Again, I refer you to JavaScript: The Definitive Guide, or to on- line JavaScript references such as the excellent Mozilla Devel- oper Network at http://developer.mozilla.org/. The examples in this book can be downloaded from the book’s web page, which will also include errata if any errors are dis- covered after publication: http://shop.oreilly.com/product/0636920011460.do viii | Preface