This book has been written for programmers, by a programmer. In order to understand it, you should already know object-oriented programming, for example, via a mainstream programming language such as Java, PHP, C++, Python, Ruby, Objective-C, Swift, C#, or Perl.
Thus, the book’s target audience is programmers who want to learn JavaScript quickly and properly, and JavaScript programmers who want to deepen their skills and/or look up specific topics.
Speaking JavaScript has four parts:
- JavaScript Quick Start: Learn a safe subset of JavaScript in less than 30 pages.
- Background: When, why, and how was JavaScript created? How is it related to other programming languages? What were the important steps that got us to where we are today?
- JavaScript in Depth: This part is more of a reference: look for a topic that you are interested in, jump in, and explore. I still tried to make it fun to read.
- Tips, Tools, and Libraries: This part gives tips for using JavaScript: best practices, advanced techniques, and learning resources. It also describes a few important tools and libraries.
- Title
- Speaking JavaScript
- Subtitle
- An In-Depth Guide for Programmers
- Publisher
- O'Reilly Media
- Author(s)
- Dr. Axel Rauschmayer
- Published
- 2014-04-22
- Edition
- 1
- Format
- eBook (pdf, epub, mobi)
- Pages
- 458
- Language
- English
- ISBN-10
- 1449365035
- ISBN-13
- 9781449365035
- License
- Read online for free
- Book Homepage
- Free eBook, Errata, Code, Solutions, etc.
Praise for Speaking JavaScript Preface What You Need to Know About This Book Tips for Reading This Book The Four Parts of This Book JavaScript Command Lines Notational Conventions Describing syntax Referring to methods Command-line interaction Tips, notes, and warnings Quickly Finding Documentation Safari® Books Online How to Contact Us Acknowledgments Preparing for JavaScript Help with JavaScript Reviewers I. JavaScript Quick Start 1. Basic JavaScript Background JavaScript Versus ECMAScript Influences and Nature of the Language Syntax An Overview of the Syntax Statements Versus Expressions Semicolons Comments Variables and Assignment Assignment Compound Assignment Operators Identifiers and Variable Names Values Primitive Values Versus Objects Primitive Values Objects undefined and null Checking for undefined or null Categorizing Values Using typeof and instanceof Booleans Truthy and Falsy Binary Logical Operators Equality Operators Numbers Operators Strings String Operators String Methods Statements Conditionals Loops Functions Function Declarations Are Hoisted The Special Variable arguments Too Many or Too Few Arguments Optional Parameters Enforcing an Arity Converting arguments to an Array Exception Handling Strict Mode Variable Scoping and Closures Variables Are Function-Scoped Variables Are Hoisted Closures The IIFE Pattern: Introducing a New Scope IIFE use case: inadvertent sharing via closures Objects and Constructors Single Objects Arbitrary Property Keys Extracting Methods Functions Inside a Method Constructors: Factories for Objects Arrays Array Literals Array Methods Iterating over Arrays Regular Expressions Method test(): Is There a Match? Method exec(): Match and Capture Groups Method replace(): Search and Replace Math Other Functionality of the Standard Library II. Background 2. Why JavaScript? Is JavaScript Freely Available? Is JavaScript Elegant? Is JavaScript Useful? Graphical User Interfaces Other Technologies Complementing JavaScript Does JavaScript Have Good Tools? Is JavaScript Fast Enough? Is JavaScript Widely Used? Does JavaScript Have a Future? Conclusion 3. The Nature of JavaScript Quirks and Unorthodox Features Elegant Parts Influences 4. How JavaScript Was Created 5. Standardization: ECMAScript 6. Historical JavaScript Milestones III. JavaScript in Depth 7. JavaScript’s Syntax An Overview of the Syntax Comments Expressions Versus Statements Expressions Statements Conditional statement versus conditional expressions Using ambiguous expressions as statements Evaluating an object literal via eval() Immediately invoking a function expression Control Flow Statements and Blocks Rules for Using Semicolons No Semicolon After a Statement Ending with a Block The Empty Statement Automatic Semicolon Insertion Example: ASI via illegal token Example: ASI via closing brace Pitfall: ASI can unexpectedly break up statements Pitfall: ASI might unexpectedly not be triggered Legal Identifiers Invoking Methods on Number Literals Strict Mode Switching on Strict Mode Strict Mode: Recommended, with Caveats Variables Must Be Declared in Strict Mode Functions in Strict Mode Functions must be declared at the top level of a scope Stricter rules for function parameters The arguments objects has fewer properties this is undefined in nonmethod functions Setting and Deleting Immutable Properties Fails with an Exception in Strict Mode Unqualified Identifiers Can’t Be Deleted in Strict Mode eval() Is Cleaner in Strict Mode Features That Are Forbidden in Strict Mode 8. Values JavaScript’s Type System JavaScript’s Types Static Versus Dynamic Static Typing Versus Dynamic Typing Static Type Checking Versus Dynamic Type Checking Coercion Primitive Values Versus Objects Primitive Values Objects undefined and null Occurrences of undefined and null Occurrences of undefined Occurrences of null Checking for undefined or null Checking for null Checking for undefined Checking for either undefined or null The History of undefined and null Changing undefined Wrapper Objects for Primitives Wrapper Objects Are Different from Primitives Wrapping and Unwrapping Primitives Primitives Borrow Their Methods from Wrappers Type Coercion Type Coercion Can Hide Bugs Functions for Converting to Boolean, Number, String, and Object Algorithm: ToPrimitive()—Converting a Value to a Primitive Examples: ToPrimitive() in action 9. Operators Operators and Objects Assignment Operators Compound Assignment Operators Equality Operators: === Versus == Strict Equality (===, !==) Pitfall: NaN Strict inequality (!==) Normal (Lenient) Equality (==, !=) Lenient inequality (!=) Pitfall: lenient equality is different from conversion to boolean Pitfall: lenient equality and strings Pitfall: lenient equality and objects There Are No Valid Use Cases for == Use case: checking for undefined or null Use case: working with numbers in strings Use case: comparing wrapper instances with primitives Ordering Operators The Algorithm The Plus Operator (+) The Algorithm Operators for Booleans and Numbers Special Operators The Conditional Operator ( ? : ) The Comma Operator The void Operator What is void used for? Why does JavaScript have a void operator? Categorizing Values via typeof and instanceof typeof: Categorizing Primitives Pitfall: typeof null The history of typeof null Checking whether a variable exists instanceof: Checking Whether an Object Is an Instance of a Given Constructor Object Operators 10. Booleans Converting to Boolean Manually Converting to Boolean Truthy and Falsy Values Pitfall: all objects are truthy History: Why are objects always truthy? Logical Operators Binary Logical Operators: And (&&) and Or (||) Logical And (&&) Logical Or (||) Pattern: providing a default value Example 1: a default for a parameter Example 2: a default for a property Example 3: a default for the result of a function Logical Not (!) Equality Operators, Ordering Operators The Function Boolean 11. Numbers Number Literals Exponent Invoking Methods on Literals Converting to Number Manually Converting to Number parseFloat() Special Number Values NaN Pitfall: checking whether a value is NaN Infinity Error: a number’s magnitude is too large Error: division by zero Computing with Infinity Checking for Infinity Two Zeros Best practice: pretend there’s only one zero Distinguishing the two zeros The Internal Representation of Numbers Special Exponents Handling Rounding Errors Integers in JavaScript Ranges of Integers Representing Integers as Floating-Point Numbers Best practice Safe Integers Definitions in ECMAScript 6 Safe results of arithmetic computations Converting to Integer Integers via Math.floor(), Math.ceil(), and Math.round() Integers via the Custom Function ToInteger() 32-bit Integers via Bitwise Operators Bitwise Or (|) Shift operators Should I use bitwise operators to coerce to integer? Integers via parseInt() The radix Explanation Summary Arithmetic Operators Bitwise Operators Background Knowledge Binary complements Signed 32-bit integers Inputting and outputting binary numbers Bitwise Not Operator Binary Bitwise Operators Bitwise Shift Operators The Function Number Number Constructor Properties Number Prototype Methods Number.prototype.toFixed(fractionDigits?) Number.prototype.toPrecision(precision?) Number.prototype.toString(radix?) Decimal exponential notation Number.prototype.toExponential(fractionDigits?) Functions for Numbers Sources for This Chapter 12. Strings String Literals Escaping in String Literals Character Access Converting to String Manually Converting to String Pitfall: conversion is not invertible Comparing Strings Concatenating Strings Concatenation: The Plus (+) Operator Concatenation: Joining an Array of String Fragments The Function String String Constructor Method String Instance Property length String Prototype Methods Extract Substrings Transform Search and Compare Test, Match, and Replace with Regular Expressions 13. Statements Declaring and Assigning Variables The Bodies of Loops and Conditionals Loops Mechanisms to Be Used with Loops while do-while for for-in Best practice: don’t use for-in for arrays Best practice: be careful with for-in for objects for each-in Conditionals if-then-else Chaining if statements Pitfall: dangling else switch The with Statement Syntax and Semantics The with Statement Is Deprecated Techniques for avoiding the with statement The Rationale for the Deprecation The debugger Statement 14. Exception Handling What Is Exception Handling? Exception Handling in JavaScript throw try-catch-finally Examples Error Constructors Stack Traces Implementing Your Own Error Constructor 15. Functions The Three Roles of Functions in JavaScript Terminology: “Parameter” Versus “Argument” Defining Functions Function Expressions Named function expressions Function Declarations The Function Constructor Hoisting The Name of a Function Which Is Better: A Function Declaration or a Function Expression? More Control over Function Calls: call(), apply(), and bind() func.apply(thisValue, argArray) func.bind(thisValue, arg1, ..., argN) Handling Missing or Extra Parameters All Parameters by Index: The Special Variable arguments Deprecated features of arguments Mandatory Parameters, Enforcing a Minimum Arity Optional Parameters Simulating Pass-by-Reference Parameters Pitfall: Unexpected Optional Parameters Named Parameters Named Parameters as Descriptions Optional Named Parameters Simulating Named Parameters in JavaScript 16. Variables: Scopes, Environments, and Closures Declaring a Variable Background: Static Versus Dynamic Background: The Scope of a Variable Variables Are Function-Scoped Variable Declarations Are Hoisted Introducing a New Scope via an IIFE IIFE Variation: Prefix Operators IIFE Variation: Already Inside Expression Context IIFE Variation: An IIFE with Parameters IIFE Applications Global Variables Best Practice: Avoid Creating Global Variables Module Systems Lead to Fewer Globals The Global Object Cross-Platform Considerations Use Cases for window Use case: marking global variables Use case: built-ins Use case: style checkers Use case: checking whether a global variable exists Use case: creating things in global scope Environments: Managing Variables Closures: Functions Stay Connected to Their Birth Scopes Handling Closures via Environments Pitfall: Inadvertently Sharing an Environment 17. Objects and Inheritance Layer 1: Single Objects Kinds of Properties Object Literals Dot Operator (.): Accessing Properties via Fixed Keys Getting properties Calling methods Setting properties Deleting properties The return value of delete Unusual Property Keys Bracket Operator ([]): Accessing Properties via Computed Keys Getting properties via the bracket operator Calling methods via the bracket operator Setting properties via the bracket operator Deleting properties via the bracket operator Converting Any Value to an Object this as an Implicit Parameter of Functions and Methods Calling Functions While Setting this: call(), apply(), and bind() Function.prototype.call(thisValue, arg1?, arg2?, ...) Function.prototype.apply(thisValue, argArray) Function.prototype.bind(thisValue, arg1?, ..., argN?) apply() for Constructors Manually simulating an apply() for constructors A library method An alternative approach Pitfall: Losing this When Extracting a Method How to get a warning How to properly extract a method Callbacks and extracted methods Pitfall: Functions Inside Methods Shadow this Workaround 1: that = this Workaround 2: bind() Workaround 3: a thisValue for forEach() Layer 2: The Prototype Relationship Between Objects Inheritance Overriding Sharing Data Between Objects via a Prototype Getting and Setting the Prototype Creating a new object with a given prototype Reading the prototype of an object Checking whether one object a prototype of another one Finding the object where a property is defined The Special Property __proto__ Setting and Deleting Affects Only Own Properties Setting a property Deleting an inherited property Changing properties anywhere in the prototype chain Iteration and Detection of Properties Listing Own Property Keys Listing All Property Keys Checking Whether a Property Exists Examples The effects of enumerability The effects of inheritance Computing the number of own properties of an object Best Practices: Iterating over Own Properties Accessors (Getters and Setters) Defining Accessors via an Object Literal Defining Accessors via Property Descriptors Accessors and Inheritance Property Attributes and Property Descriptors Property Attributes Default values Property Descriptors Getting and Defining Properties via Descriptors Copying an Object Properties: Definition Versus Assignment Inherited Read-Only Properties Can’t Be Assigned To Enumerability: Best Practices Protecting Objects Preventing Extensions Sealing Freezing Pitfall: Protection Is Shallow Layer 3: Constructors—Factories for Instances The new Operator Implemented in JavaScript Terminology: The Two Prototypes The constructor Property of Instances Use cases for the constructor property Best practice The instanceof Operator Pitfall: objects that are not instances of Object Pitfall: crossing realms (frames or windows) Tips for Implementing Constructors Protection against forgetting new: strict mode Returning arbitrary objects from a constructor Data in Prototype Properties Avoid Prototype Properties with Initial Values for Instance Properties Best practice: don’t share default values Creating instance properties on demand Avoid Nonpolymorphic Prototype Properties Polymorphic Prototype Properties Keeping Data Private Private Data in the Environment of a Constructor (Crockford Privacy Pattern) Public properties Private values Privileged methods An example The pros and cons of the Crockford privacy pattern Private Data in Properties with Marked Keys Private Data in Properties with Reified Keys Keeping Global Data Private via IIFEs Attaching private global data to a singleton object Keeping global data private to all of a constructor Attaching global data to a method Layer 4: Inheritance Between Constructors Inheriting Instance Properties Inheriting Prototype Properties Ensuring That instanceof Works Overriding a Method Making a Supercall Avoiding Hardcoding the Name of the Superconstructor Example: Constructor Inheritance in Use Example: The Inheritance Hierarchy of Built-in Constructors Antipattern: The Prototype Is an Instance of the Superconstructor Methods of All Objects Conversion to Primitive Object.prototype.toLocaleString() Prototypal Inheritance and Properties Generic Methods: Borrowing Methods from Prototypes Accessing Object.prototype and Array.prototype via Literals Examples of Calling Methods Generically Array-Like Objects and Generic Methods Patterns for working with array-like objects A List of All Generic Methods Pitfalls: Using an Object as a Map Pitfall 1: Inheritance Affects Reading Properties Checking whether a property exists Collecting property keys Getting a property value Pitfall 2: Overriding Affects Invoking Methods Pitfall 3: The Special Property __proto__ The dict Pattern: Objects Without Prototypes Are Better Maps Normal objects Prototype-less objects Recommendation Best Practices Cheat Sheet: Working with Objects 18. Arrays Overview Arrays Are Maps, Not Tuples Arrays Can Also Have Properties Creating Arrays The Array Constructor Creating an empty array with a given length Initializing an array with elements (avoid!) Multidimensional Arrays Array Indices The in Operator and Indices Deleting Array Elements Array Indices in Detail length Manually Increasing the Length of an Array Decreasing the Length of an Array Clearing an array Clearing shared arrays The Maximum Length Holes in Arrays Creating Holes Sparse Arrays Versus Dense Arrays Which Operations Ignore Holes, and Which Consider Them? Array iteration methods Other array methods The for-in loop Function.prototype.apply() Removing Holes from Arrays Array Constructor Method Array Prototype Methods Adding and Removing Elements (Destructive) Sorting and Reversing Elements (Destructive) Comparing Numbers Comparing Strings Comparing Objects Concatenating, Slicing, Joining (Nondestructive) Searching for Values (Nondestructive) Iteration (Nondestructive) Examination Methods Transformation Methods Reduction Methods Pitfall: Array-Like Objects Best Practices: Iterating over Arrays 19. Regular Expressions Regular Expression Syntax Atoms: General Atoms: Character Classes Atoms: Groups Quantifiers Assertions Disjunction Unicode and Regular Expressions Creating a Regular Expression Literal Versus Constructor Flags Instance Properties of Regular Expressions Examples of Creating Regular Expressions RegExp.prototype.test: Is There a Match? String.prototype.search: At What Index Is There a Match? RegExp.prototype.exec: Capture Groups First Match (Flag /g Not Set) All Matches (Flag /g Set) String.prototype.match: Capture Groups or Return All Matching Substrings String.prototype.replace: Search and Replace Replacement Is a String Replacement Is a Function Problems with the Flag /g Tips and Tricks Quoting Text Pitfall: Without an Assertion (e.g., ^, $), a Regular Expression Is Found Anywhere Matching Everything or Nothing Matching everything Matching nothing Manually Implementing Lookbehind Regular Expression Cheat Sheet 20. Dates The Date Constructor Date Constructor Methods Date Prototype Methods Time Unit Getters and Setters Various Getters and Setters Convert a Date to a String Date Time Formats Date Formats (No Time) Time Formats (No Date) Date Time Formats Time Values: Dates as Milliseconds Since 1970-01-01 Converting a Date to a Number 21. Math Math Properties Numerical Functions Trigonometric Functions Other Functions 22. JSON Background Data Format History Grammar JSON.stringify(value, replacer?, space?) Data Ignored by JSON.stringify() The toJSON() Method JSON.parse(text, reviver?) Transforming Data via Node Visitors JSON.stringify() JSON.parse() 23. Standard Global Variables Constructors Error Constructors Nonconstructor Functions Encoding and Decoding Text Categorizing and Parsing Numbers Dynamically Evaluating JavaScript Code via eval() and new Function() Evaluating Code Using eval() Use eval() in strict mode Indirect eval() evaluates in global scope Evaluating Code Using new Function() eval() Versus new Function() Best Practices Legitimate use cases Conclusion The Console API How Standardized Is the Console API Across Engines? Simple Logging Checking and Counting Formatted Logging Profiling and Timing Namespaces and Special Values 24. Unicode and JavaScript Unicode History Important Unicode Concepts Code Points Unicode Encodings JavaScript Source Code and Unicode Source Code Internally Source Code Externally JavaScript Strings and Unicode Escape Sequences Refering to Astral Plane Characters via Escapes Counting Characters Unicode Normalization JavaScript Regular Expressions and Unicode Matching Any Code Unit and Any Code Point Libraries Recommended Reading and Chapter Sources 25. New in ECMAScript 5 New Features Syntactic Changes New Functionality in the Standard Library Metaprogramming New Methods JSON Tips for Working with Legacy Browsers IV. Tips, Tools, and Libraries 26. A Meta Code Style Guide Existing Style Guides General Tips Code Should Be Consistent Code Should Be Easy to Understand Commonly Accepted Best Practices Brace Styles Allman style 1TBS (One True Brace Style) JavaScript Prefer Literals to Constructors Don’t Be Clever Conditional operator Abbreviating if statements Increment operator Checking for undefined Converting a number to an integer Acceptable Cleverness Default values Generic methods ECMAScript 5: trailing commas ECMAScript 5: reserved words Controversial Rules Syntax Variables Object Orientation Miscellaneous Conclusion 27. Language Mechanisms for Debugging 28. Subclassing Built-ins Terminology Obstacle 1: Instances with Internal Properties Workaround for Obstacle 1 Caveats Obstacle 2: A Constructor That Can’t Be Called as a Function Workaround for Obstacle 2 Another Solution: Delegation 29. JSDoc: Generating API Documentation The Basics of JSDoc Syntax Naming Types Basic Tags Documenting Functions and Methods Inline Type Information (“Inline Doc Comments”) Documenting Variables, Parameters, and Instance Properties Documenting Classes Defining a Class via a Constructor Function Defining a Class via an Object Literal Defining a Class via an Object Literal with an @constructs Method Subclassing Other Useful Tags 30. Libraries Shims Versus Polyfills Four Language Libraries The ECMAScript Internationalization API The ECMAScript Internationalization API, Edition 1 What Kind of Standard Is It? When Can I Use It? Further Reading Directories for JavaScript Resources 31. Module Systems and Package Managers Module Systems Package Managers Quick and Dirty Modules 32. More Tools 33. What to Do Next Index About the Author Colophon Copyright
Related Books