Speaking JavaScript
Homepage
Buy the book
(Ad, please don’t block.)

Table of contents

  1. Praise for Speaking JavaScript
  2. Preface
    1. What You Need to Know About This Book
    2. Tips for Reading This Book
      1. The Four Parts of This Book
      2. JavaScript Command Lines
      3. Notational Conventions
        1. Describing syntax
        2. Referring to methods
        3. Command-line interaction
        4. Tips, notes, and warnings
      4. Quickly Finding Documentation
    3. Safari® Books Online
    4. How to Contact Us
    5. Acknowledgments
      1. Preparing for JavaScript
      2. Help with JavaScript
      3. Reviewers
  3. I. JavaScript Quick Start
    1. 1. Basic JavaScript
      1. Background
        1. JavaScript Versus ECMAScript
        2. Influences and Nature of the Language
      2. Syntax
        1. An Overview of the Syntax
        2. Statements Versus Expressions
        3. Semicolons
        4. Comments
      3. Variables and Assignment
        1. Assignment
        2. Compound Assignment Operators
        3. Identifiers and Variable Names
      4. Values
        1. Primitive Values Versus Objects
        2. Primitive Values
        3. Objects
        4. undefined and null
        5. Categorizing Values Using typeof and instanceof
      5. Booleans
        1. Truthy and Falsy
        2. Binary Logical Operators
        3. Equality Operators
      6. Numbers
      7. Operators
      8. Strings
        1. String Operators
        2. String Methods
      9. Statements
        1. Conditionals
        2. Loops
      10. Functions
        1. Function Declarations Are Hoisted
        2. The Special Variable arguments
        3. Too Many or Too Few Arguments
        4. Optional Parameters
        5. Enforcing an Arity
        6. Converting arguments to an Array
      11. Exception Handling
      12. Strict Mode
      13. Variable Scoping and Closures
        1. Variables Are Function-Scoped
        2. Variables Are Hoisted
        3. Closures
        4. The IIFE Pattern: Introducing a New Scope
      14. Objects and Constructors
        1. Single Objects
        2. Arbitrary Property Keys
        3. Extracting Methods
        4. Functions Inside a Method
        5. Constructors: Factories for Objects
      15. Arrays
        1. Array Literals
        2. Array Methods
        3. Iterating over Arrays
      16. Regular Expressions
        1. Method test(): Is There a Match?
        2. Method exec(): Match and Capture Groups
        3. Method replace(): Search and Replace
      17. Math
      18. Other Functionality of the Standard Library
  4. II. Background
    1. 2. Why JavaScript?
      1. Is JavaScript Freely Available?
      2. Is JavaScript Elegant?
      3. Is JavaScript Useful?
        1. Graphical User Interfaces
        2. Other Technologies Complementing JavaScript
      4. Does JavaScript Have Good Tools?
      5. Is JavaScript Fast Enough?
      6. Is JavaScript Widely Used?
      7. Does JavaScript Have a Future?
      8. Conclusion
    2. 3. The Nature of JavaScript
      1. Quirks and Unorthodox Features
      2. Elegant Parts
      3. Influences
    3. 4. How JavaScript Was Created
    4. 5. Standardization: ECMAScript
    5. 6. Historical JavaScript Milestones
  5. III. JavaScript in Depth
    1. 7. JavaScript’s Syntax
      1. An Overview of the Syntax
      2. Comments
      3. Expressions Versus Statements
        1. Expressions
        2. Statements
      4. Control Flow Statements and Blocks
      5. Rules for Using Semicolons
        1. No Semicolon After a Statement Ending with a Block
        2. The Empty Statement
        3. Automatic Semicolon Insertion
      6. Legal Identifiers
      7. Invoking Methods on Number Literals
      8. Strict Mode
        1. Switching on Strict Mode
        2. Strict Mode: Recommended, with Caveats
        3. Variables Must Be Declared in Strict Mode
        4. Functions in Strict Mode
        5. Setting and Deleting Immutable Properties Fails with an Exception in Strict Mode
        6. Unqualified Identifiers Can’t Be Deleted in Strict Mode
        7. eval() Is Cleaner in Strict Mode
        8. Features That Are Forbidden in Strict Mode
    2. 8. Values
      1. JavaScript’s Type System
        1. JavaScript’s Types
        2. Static Versus Dynamic
        3. Static Typing Versus Dynamic Typing
        4. Static Type Checking Versus Dynamic Type Checking
        5. Coercion
      2. Primitive Values Versus Objects
      3. Primitive Values
      4. Objects
      5. undefined and null
        1. Occurrences of undefined and null
        2. Checking for undefined or null
        3. The History of undefined and null
        4. Changing undefined
      6. Wrapper Objects for Primitives
        1. Wrapper Objects Are Different from Primitives
        2. Wrapping and Unwrapping Primitives
        3. Primitives Borrow Their Methods from Wrappers
      7. Type Coercion
        1. Type Coercion Can Hide Bugs
        2. Functions for Converting to Boolean, Number, String, and Object
        3. Algorithm: ToPrimitive()—Converting a Value to a Primitive
    3. 9. Operators
      1. Operators and Objects
      2. Assignment Operators
        1. Compound Assignment Operators
      3. Equality Operators: === Versus ==
        1. Strict Equality (===, !==)
        2. Normal (Lenient) Equality (==, !=)
        3. There Are No Valid Use Cases for ==
      4. Ordering Operators
        1. The Algorithm
      5. The Plus Operator (+)
        1. The Algorithm
      6. Operators for Booleans and Numbers
      7. Special Operators
        1. The Conditional Operator ( ? : )
        2. The Comma Operator
        3. The void Operator
      8. Categorizing Values via typeof and instanceof
        1. typeof: Categorizing Primitives
        2. instanceof: Checking Whether an Object Is an Instance of a Given Constructor
      9. Object Operators
    4. 10. Booleans
      1. Converting to Boolean
        1. Manually Converting to Boolean
        2. Truthy and Falsy Values
      2. Logical Operators
        1. Binary Logical Operators: And (&&) and Or (||)
        2. Logical And (&&)
        3. Logical Or (||)
        4. Logical Not (!)
      3. Equality Operators, Ordering Operators
      4. The Function Boolean
    5. 11. Numbers
      1. Number Literals
        1. Exponent
        2. Invoking Methods on Literals
      2. Converting to Number
        1. Manually Converting to Number
        2. parseFloat()
      3. Special Number Values
        1. NaN
        2. Infinity
        3. Two Zeros
      4. The Internal Representation of Numbers
        1. Special Exponents
      5. Handling Rounding Errors
      6. Integers in JavaScript
        1. Ranges of Integers
        2. Representing Integers as Floating-Point Numbers
        3. Safe Integers
      7. Converting to Integer
        1. Integers via Math.floor(), Math.ceil(), and Math.round()
        2. Integers via the Custom Function ToInteger()
        3. 32-bit Integers via Bitwise Operators
        4. Integers via parseInt()
      8. Arithmetic Operators
      9. Bitwise Operators
        1. Background Knowledge
        2. Bitwise Not Operator
        3. Binary Bitwise Operators
        4. Bitwise Shift Operators
      10. The Function Number
      11. Number Constructor Properties
      12. Number Prototype Methods
        1. Number.prototype.toFixed(fractionDigits?)
        2. Number.prototype.toPrecision(precision?)
        3. Number.prototype.toString(radix?)
        4. Number.prototype.toExponential(fractionDigits?)
      13. Functions for Numbers
      14. Sources for This Chapter
    6. 12. Strings
      1. String Literals
      2. Escaping in String Literals
      3. Character Access
      4. Converting to String
        1. Manually Converting to String
      5. Comparing Strings
      6. Concatenating Strings
        1. Concatenation: The Plus (+) Operator
        2. Concatenation: Joining an Array of String Fragments
      7. The Function String
      8. String Constructor Method
      9. String Instance Property length
      10. String Prototype Methods
        1. Extract Substrings
        2. Transform
        3. Search and Compare
        4. Test, Match, and Replace with Regular Expressions
    7. 13. Statements
      1. Declaring and Assigning Variables
      2. The Bodies of Loops and Conditionals
      3. Loops
        1. Mechanisms to Be Used with Loops
        2. while
        3. do-while
        4. for
        5. for-in
        6. for each-in
      4. Conditionals
        1. if-then-else
        2. switch
      5. The with Statement
        1. Syntax and Semantics
        2. The with Statement Is Deprecated
        3. The Rationale for the Deprecation
      6. The debugger Statement
    8. 14. Exception Handling
      1. What Is Exception Handling?
      2. Exception Handling in JavaScript
        1. throw
        2. try-catch-finally
        3. Examples
      3. Error Constructors
      4. Stack Traces
      5. Implementing Your Own Error Constructor
    9. 15. Functions
      1. The Three Roles of Functions in JavaScript
      2. Terminology: “Parameter” Versus “Argument”
      3. Defining Functions
        1. Function Expressions
        2. Function Declarations
        3. The Function Constructor
      4. Hoisting
      5. The Name of a Function
      6. Which Is Better: A Function Declaration or a Function Expression?
      7. More Control over Function Calls: call(), apply(), and bind()
        1. func.apply(thisValue, argArray)
        2. func.bind(thisValue, arg1, ..., argN)
      8. Handling Missing or Extra Parameters
        1. All Parameters by Index: The Special Variable arguments
        2. Mandatory Parameters, Enforcing a Minimum Arity
        3. Optional Parameters
        4. Simulating Pass-by-Reference Parameters
        5. Pitfall: Unexpected Optional Parameters
      9. Named Parameters
        1. Named Parameters as Descriptions
        2. Optional Named Parameters
        3. Simulating Named Parameters in JavaScript
    10. 16. Variables: Scopes, Environments, and Closures
      1. Declaring a Variable
      2. Background: Static Versus Dynamic
      3. Background: The Scope of a Variable
      4. Variables Are Function-Scoped
      5. Variable Declarations Are Hoisted
      6. Introducing a New Scope via an IIFE
        1. IIFE Variation: Prefix Operators
        2. IIFE Variation: Already Inside Expression Context
        3. IIFE Variation: An IIFE with Parameters
        4. IIFE Applications
      7. Global Variables
        1. Best Practice: Avoid Creating Global Variables
        2. Module Systems Lead to Fewer Globals
      8. The Global Object
        1. Cross-Platform Considerations
        2. Use Cases for window
      9. Environments: Managing Variables
      10. Closures: Functions Stay Connected to Their Birth Scopes
        1. Handling Closures via Environments
        2. Pitfall: Inadvertently Sharing an Environment
    11. 17. Objects and Inheritance
      1. Layer 1: Single Objects
        1. Kinds of Properties
        2. Object Literals
        3. Dot Operator (.): Accessing Properties via Fixed Keys
        4. Unusual Property Keys
        5. Bracket Operator ([]): Accessing Properties via Computed Keys
      2. Converting Any Value to an Object
      3. this as an Implicit Parameter of Functions and Methods
        1. Calling Functions While Setting this: call(), apply(), and bind()
        2. apply() for Constructors
        3. Pitfall: Losing this When Extracting a Method
        4. Pitfall: Functions Inside Methods Shadow this
      4. Layer 2: The Prototype Relationship Between Objects
        1. Inheritance
        2. Overriding
        3. Sharing Data Between Objects via a Prototype
        4. Getting and Setting the Prototype
        5. The Special Property __proto__
        6. Setting and Deleting Affects Only Own Properties
      5. Iteration and Detection of Properties
        1. Listing Own Property Keys
        2. Listing All Property Keys
        3. Checking Whether a Property Exists
        4. Examples
      6. Best Practices: Iterating over Own Properties
      7. Accessors (Getters and Setters)
        1. Defining Accessors via an Object Literal
        2. Defining Accessors via Property Descriptors
        3. Accessors and Inheritance
      8. Property Attributes and Property Descriptors
        1. Property Attributes
        2. Property Descriptors
        3. Getting and Defining Properties via Descriptors
        4. Copying an Object
        5. Properties: Definition Versus Assignment
        6. Inherited Read-Only Properties Can’t Be Assigned To
        7. Enumerability: Best Practices
      9. Protecting Objects
        1. Preventing Extensions
        2. Sealing
        3. Freezing
        4. Pitfall: Protection Is Shallow
      10. Layer 3: Constructors—Factories for Instances
        1. The new Operator Implemented in JavaScript
        2. Terminology: The Two Prototypes
        3. The constructor Property of Instances
        4. The instanceof Operator
        5. Tips for Implementing Constructors
      11. Data in Prototype Properties
        1. Avoid Prototype Properties with Initial Values for Instance Properties
        2. Avoid Nonpolymorphic Prototype Properties
        3. Polymorphic Prototype Properties
      12. Keeping Data Private
        1. Private Data in the Environment of a Constructor (Crockford Privacy Pattern)
        2. Private Data in Properties with Marked Keys
        3. Private Data in Properties with Reified Keys
        4. Keeping Global Data Private via IIFEs
      13. Layer 4: Inheritance Between Constructors
        1. Inheriting Instance Properties
        2. Inheriting Prototype Properties
        3. Ensuring That instanceof Works
        4. Overriding a Method
        5. Making a Supercall
        6. Avoiding Hardcoding the Name of the Superconstructor
        7. Example: Constructor Inheritance in Use
        8. Example: The Inheritance Hierarchy of Built-in Constructors
        9. Antipattern: The Prototype Is an Instance of the Superconstructor
      14. Methods of All Objects
        1. Conversion to Primitive
        2. Object.prototype.toLocaleString()
        3. Prototypal Inheritance and Properties
      15. Generic Methods: Borrowing Methods from Prototypes
        1. Accessing Object.prototype and Array.prototype via Literals
        2. Examples of Calling Methods Generically
        3. Array-Like Objects and Generic Methods
        4. A List of All Generic Methods
      16. Pitfalls: Using an Object as a Map
        1. Pitfall 1: Inheritance Affects Reading Properties
        2. Pitfall 2: Overriding Affects Invoking Methods
        3. Pitfall 3: The Special Property __proto__
        4. The dict Pattern: Objects Without Prototypes Are Better Maps
        5. Best Practices
      17. Cheat Sheet: Working with Objects
    12. 18. Arrays
      1. Overview
        1. Arrays Are Maps, Not Tuples
        2. Arrays Can Also Have Properties
      2. Creating Arrays
        1. The Array Constructor
        2. Multidimensional Arrays
      3. Array Indices
        1. The in Operator and Indices
        2. Deleting Array Elements
        3. Array Indices in Detail
      4. length
        1. Manually Increasing the Length of an Array
        2. Decreasing the Length of an Array
        3. The Maximum Length
      5. Holes in Arrays
        1. Creating Holes
        2. Sparse Arrays Versus Dense Arrays
        3. Which Operations Ignore Holes, and Which Consider Them?
        4. Removing Holes from Arrays
      6. Array Constructor Method
      7. Array Prototype Methods
      8. Adding and Removing Elements (Destructive)
      9. Sorting and Reversing Elements (Destructive)
        1. Comparing Numbers
        2. Comparing Strings
        3. Comparing Objects
      10. Concatenating, Slicing, Joining (Nondestructive)
      11. Searching for Values (Nondestructive)
      12. Iteration (Nondestructive)
        1. Examination Methods
        2. Transformation Methods
        3. Reduction Methods
      13. Pitfall: Array-Like Objects
      14. Best Practices: Iterating over Arrays
    13. 19. Regular Expressions
      1. Regular Expression Syntax
        1. Atoms: General
        2. Atoms: Character Classes
        3. Atoms: Groups
        4. Quantifiers
        5. Assertions
        6. Disjunction
      2. Unicode and Regular Expressions
      3. Creating a Regular Expression
        1. Literal Versus Constructor
        2. Flags
        3. Instance Properties of Regular Expressions
        4. Examples of Creating Regular Expressions
      4. RegExp.prototype.test: Is There a Match?
      5. String.prototype.search: At What Index Is There a Match?
      6. RegExp.prototype.exec: Capture Groups
        1. First Match (Flag /g Not Set)
        2. All Matches (Flag /g Set)
      7. String.prototype.match: Capture Groups or Return All Matching Substrings
      8. String.prototype.replace: Search and Replace
        1. Replacement Is a String
        2. Replacement Is a Function
      9. Problems with the Flag /g
      10. Tips and Tricks
        1. Quoting Text
        2. Pitfall: Without an Assertion (e.g., ^, $), a Regular Expression Is Found Anywhere
        3. Matching Everything or Nothing
        4. Manually Implementing Lookbehind
      11. Regular Expression Cheat Sheet
    14. 20. Dates
      1. The Date Constructor
      2. Date Constructor Methods
      3. Date Prototype Methods
        1. Time Unit Getters and Setters
        2. Various Getters and Setters
        3. Convert a Date to a String
      4. Date Time Formats
        1. Date Formats (No Time)
        2. Time Formats (No Date)
        3. Date Time Formats
      5. Time Values: Dates as Milliseconds Since 1970-01-01
        1. Converting a Date to a Number
    15. 21. Math
      1. Math Properties
      2. Numerical Functions
      3. Trigonometric Functions
      4. Other Functions
    16. 22. JSON
      1. Background
        1. Data Format
        2. History
        3. Grammar
      2. JSON.stringify(value, replacer?, space?)
        1. Data Ignored by JSON.stringify()
        2. The toJSON() Method
      3. JSON.parse(text, reviver?)
      4. Transforming Data via Node Visitors
        1. JSON.stringify()
        2. JSON.parse()
    17. 23. Standard Global Variables
      1. Constructors
      2. Error Constructors
      3. Nonconstructor Functions
        1. Encoding and Decoding Text
        2. Categorizing and Parsing Numbers
      4. Dynamically Evaluating JavaScript Code via eval() and new Function()
        1. Evaluating Code Using eval()
        2. Evaluating Code Using new Function()
        3. eval() Versus new Function()
        4. Best Practices
        5. Conclusion
      5. The Console API
        1. How Standardized Is the Console API Across Engines?
        2. Simple Logging
        3. Checking and Counting
        4. Formatted Logging
        5. Profiling and Timing
      6. Namespaces and Special Values
    18. 24. Unicode and JavaScript
      1. Unicode History
      2. Important Unicode Concepts
      3. Code Points
      4. Unicode Encodings
      5. JavaScript Source Code and Unicode
        1. Source Code Internally
        2. Source Code Externally
      6. JavaScript Strings and Unicode
        1. Escape Sequences
        2. Refering to Astral Plane Characters via Escapes
        3. Counting Characters
        4. Unicode Normalization
      7. JavaScript Regular Expressions and Unicode
        1. Matching Any Code Unit and Any Code Point
        2. Libraries
        3. Recommended Reading and Chapter Sources
    19. 25. New in ECMAScript 5
      1. New Features
      2. Syntactic Changes
      3. New Functionality in the Standard Library
        1. Metaprogramming
        2. New Methods
        3. JSON
      4. Tips for Working with Legacy Browsers
  6. IV. Tips, Tools, and Libraries
    1. 26. A Meta Code Style Guide
      1. Existing Style Guides
      2. General Tips
        1. Code Should Be Consistent
        2. Code Should Be Easy to Understand
      3. Commonly Accepted Best Practices
        1. Brace Styles
        2. Prefer Literals to Constructors
        3. Don’t Be Clever
        4. Acceptable Cleverness
      4. Controversial Rules
        1. Syntax
        2. Variables
        3. Object Orientation
        4. Miscellaneous
      5. Conclusion
    2. 27. Language Mechanisms for Debugging
    3. 28. Subclassing Built-ins
      1. Terminology
      2. Obstacle 1: Instances with Internal Properties
        1. Workaround for Obstacle 1
        2. Caveats
      3. Obstacle 2: A Constructor That Can’t Be Called as a Function
        1. Workaround for Obstacle 2
      4. Another Solution: Delegation
    4. 29. JSDoc: Generating API Documentation
      1. The Basics of JSDoc
        1. Syntax
        2. Naming Types
      2. Basic Tags
      3. Documenting Functions and Methods
      4. Inline Type Information (“Inline Doc Comments”)
      5. Documenting Variables, Parameters, and Instance Properties
      6. Documenting Classes
        1. Defining a Class via a Constructor Function
        2. Defining a Class via an Object Literal
        3. Defining a Class via an Object Literal with an @constructs Method
        4. Subclassing
      7. Other Useful Tags
    5. 30. Libraries
      1. Shims Versus Polyfills
      2. Four Language Libraries
      3. The ECMAScript Internationalization API
        1. The ECMAScript Internationalization API, Edition 1
        2. What Kind of Standard Is It?
        3. When Can I Use It?
        4. Further Reading
      4. Directories for JavaScript Resources
    6. 31. Module Systems and Package Managers
      1. Module Systems
      2. Package Managers
      3. Quick and Dirty Modules
    7. 32. More Tools
    8. 33. What to Do Next
  7. Index
  8. About the Author
  9. Colophon
  10. Copyright