JavaScript Cookbook, 3rd Edition

Book description

Why reinvent the wheel every time you run into a problem with JavaScript? This cookbook is chock-full of code recipes for common programming tasks, along with techniques for building apps that work in any browser. You'll get adaptable code samples that you can add to almost any project--and you'll learn more about JavaScript in the process.

The recipes in this book take advantage of the latest features in ECMAScript 2020 and beyond and use modern JavaScript coding standards. You'll learn how to:

  • Set up a productive development environment with a code editor, linter, and test server
  • Work with JavaScript data types, such as strings, arrays, and BigInts
  • Improve your understanding of JavaScript functions, including arrow functions, closures, and generators
  • Apply object-oriented programming concepts like classes and inheritance
  • Work with rich media in JavaScript, including audio, video, and SVGs
  • Manipulate HTML markup and CSS styles
  • Use JavaScript anywhere with Node.js
  • Access and manipulate remote data with REST, GraphQL, and Fetch
  • Get started with the popular Express application-building framework
  • Perform asynchronous operations with Promises, async/await, and web workers

Table of contents

  1. Preface
    1. Book Audience
    2. Book Organization
    3. Conventions Used in This Book
    4. Using Code Examples
    5. O’Reilly Online Learning
    6. How to Contact Us
    7. Acknowledgments
  2. I. The JavaScript Language
  3. 1. Setting Up a Development Environment
    1. Choosing a Code Editor
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    2. Using the Developer Console in Your Browser
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    3. Running Blocks of Code in the Developer Console
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    4. Using Strict Mode to Catch Common Mistakes
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    5. Filling in HTML Boilerplate with Emmet Shortcuts
      1. Problem
      2. Solution
      3. Discussion
    6. Installing the npm Package Manager (with Node.js)
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
      5. Extra: Using a Terminal and Shell
    7. Downloading a Package with npm
      1. Problem
      2. Solution
      3. Discussion
      4. Extra: Understanding package.json
    8. Updating a Package with npm
      1. Problem
      2. Solution
      3. Discussion
    9. Setting Up a Local Test Server
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    10. Enforcing Code Standards with a Linter
      1. Problem
      2. Solution
      3. Discussion
    11. Styling Code Consistently with a Formatter
      1. Problem
      2. Solution
      3. Discussion
    12. Experimenting in a JavaScript Playground
      1. Problem
      2. Solution
      3. Discussion
  4. 2. Strings and Regular Expressions
    1. Checking for an Existing, Nonempty String
      1. Problem
      2. Solution
      3. Discussion
    2. Converting a Numeric Value to a Formatted String
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    3. Inserting Special Characters
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    4. Inserting Emojis
      1. Problem
      2. Solution
      3. Discussion
    5. Using Template Literals for Clearer String Concatenation
      1. Problem
      2. Solution
      3. Discussion
    6. Performing a Case-Insensitive String Comparison
      1. Problem
      2. Solution
      3. Discussion
    7. Checking If a String Contains a Specific Substring
      1. Problem
      2. Solution
      3. Discussion
    8. Replacing All Occurrences of a String
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    9. Replacing HTML Tags with Named Entities
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    10. Using a Regular Expression to Replace Patterns in a String
      1. Problem
      2. Solution
      3. Discussion
      4. Extra: Regular Expressions
    11. Extracting a List from a String
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    12. Finding All Instances of a Pattern
      1. Problem
      2. Solution
      3. Discussion
      4. Extra: Highlighting Matches
    13. Removing Whitespace from the Beginning and End of a String
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    14. Converting the First Letter of a String to Uppercase
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    15. Validating an Email Address
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
  5. 3. Numbers
    1. Generating Random Numbers
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    2. Generating Cryptographically Secure Random Numbers
      1. Problem
      2. Solution
      3. Discussion
    3. Rounding to a Specific Decimal Place
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    4. Preserving Accuracy in Decimal Values
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    5. Converting a String to a Number
      1. Problem
      2. Solution
      3. Discussion
    6. Converting a Decimal to a Hexadecimal Value
      1. Problem
      2. Solution
      3. Discussion
    7. Converting Between Degrees and Radians
      1. Problem
      2. Solution
      3. Discussion
    8. Calculating the Length of a Circular Arc
      1. Problem
      2. Solution
      3. Discussion
    9. Manipulating Very Large Numbers with BigInt
      1. Problem
      2. Solution
      3. Discussion
  6. 4. Dates
    1. Getting the Current Date and Time
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    2. Converting a String to a Date
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    3. Adding Days to a Date
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    4. Comparing Dates and Testing Dates for Equality
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    5. Calculating the Time Elapsed Between Two Dates
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    6. Formatting a Date Value as a String
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
  7. 5. Arrays
    1. Checking If an Object Is an Array
      1. Problem
      2. Solution
      3. Discussion
    2. Iterating Over All the Elements in an Array
      1. Problem
      2. Solution
      3. Discussion
    3. Checking If Two Arrays Are Equal
      1. Problem
      2. Solution
      3. Discussion
    4. Breaking Down an Array into Separate Variables
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    5. Passing an Array to a Function That Expects a List of Values
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    6. Cloning an Array
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    7. Merging Two Arrays
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    8. Copying a Portion of an Array by Position
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    9. Extracting Array Items That Meet Specific Criteria
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    10. Emptying an Array
      1. Problem
      2. Solution
      3. Discussion
    11. Removing Duplicate Values
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    12. Flattening a Two-Dimensional Array
      1. Problem
      2. Solution
      3. Discussion
    13. Searching Through an Array for Exact Matches
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    14. Searching Through an Array for Items That Meet Specific Criteria
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    15. Removing or Replacing Array Elements
      1. Problem
      2. Solution
      3. Discussion
    16. Sorting an Array of Objects by a Property Value
      1. Problem
      2. Solution
      3. Discussion
    17. Transforming Every Element of an Array
      1. Problem
      2. Solution
      3. Discussion
    18. Combining an Array’s Values in a Single Calculation
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    19. Validating Array Contents
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    20. Creating a Collection of Nonduplicated Values
      1. Problem
      2. Solution
      3. Discussion
    21. Creating a Key-Indexed Collection of Items
      1. Problem
      2. Solution
      3. Discussion
  8. 6. Functions
    1. Passing a Function as an Argument to Another Function
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    2. Using Arrow Functions
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    3. Providing a Default Parameter Value
      1. Problem
      2. Solution
      3. Discussion
    4. Creating a Function That Accepts Unlimited Arguments
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    5. Using Named Function Parameters
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    6. Creating a Function That Stores its State with a Closure
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    7. Creating a Generator Function That Yields Multiple Values
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
      5. Extra: Building a Repeatable Pseudorandom Number Generator
    8. Reducing Redundancy by Using Partial Application
      1. Problem
      2. Solution
      3. Discussion
      4. Advanced: A Partial Function Factory
      5. Extra: Using bind() to Partially Provide Arguments
    9. Fixing this with Function Binding
      1. Problem
      2. Solution
      3. Discussion
      4. Extra: self = this
    10. Implementing a Recursive Algorithm
      1. Problem
      2. Solution
      3. Discussion
  9. 7. Objects
    1. Checking if an Object Is a Certain Type
      1. Problem
      2. Solution
      3. Discussion
    2. Using an Object Literal to Bundle Data
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
      5. Extra: Computed Property Names
    3. Checking If an Object Has a Property
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    4. Iterating Over All the Properties of an Object
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    5. Testing for an Empty Object
      1. Problem
      2. Solution
      3. Discussion
    6. Merging the Properties of Two Objects
      1. Problem
      2. Solution
      3. Discussion
    7. Customizing the Way a Property Is Defined
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    8. Preventing Any Changes to an Object
      1. Problem
      2. Solution
      3. Discussion
    9. Intercepting and Changing Actions on an Object with a Proxy
      1. Problem
      2. Solution
      3. Discussion
    10. Cloning an Object
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    11. Making a Deep Copy of an Object
      1. Problem
      2. Solution
      3. Discussion
    12. Creating Absolutely Unique Object Property Keys
      1. Problem
      2. Solution
      3. Discussion
    13. Creating Enums with Symbol
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
  10. 8. Classes
    1. Creating a Reusable Class
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
      5. Extra: Multiple Constructors
    2. Adding Properties to a Class
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
      5. Extra: Private Fields
    3. Giving a Class a Better String Representation
      1. Problem
      2. Solution
      3. Discussion
    4. Using the Constructor Pattern to Make a Custom Class
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    5. Supporting Method Chaining in Your Class
      1. Problem
      2. Solution
      3. Discussion
    6. Adding Static Methods to a Class
      1. Problem
      2. Solution
      3. Discussion
    7. Using a Static Method to Create Objects
      1. Problem
      2. Solution
      3. Discussion
    8. Inheriting Functionality from Another Class
      1. Problem
      2. Solution
      3. Discussion
      4. Extra: Prototype Chains
    9. Organizing Your JavaScript Classes with Modules
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
  11. 9. Asynchronous Programming
    1. Updating the Page During a Loop
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    2. Using a Function That Returns a Promise
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    3. Promisifying an Asynchronous Function That Uses a Callback
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    4. Executing Multiple Promises Concurrently
      1. Problem
      2. Solution
      3. Discussion
    5. Waiting for a Promise to Finish with Await and Async
      1. Problem
      2. Solution
      3. Discussion
    6. Creating an Asynchronous Generator Function
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    7. Using a Web Worker to Perform a Background Task
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    8. Adding Progress Support to a Web Worker
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
  12. 10. Errors and Testing
    1. Catching and Neutralizing an Error
      1. Problem
      2. Solution
      3. Solution
      4. See Also
    2. Catching Different Types of Errors
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    3. Catching Asynchronous Errors
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    4. Detecting Unhandled Errors
      1. Problem
      2. Solution
      3. Discussion
      4. Extra: Logging Tools
    5. Throwing a Standard Error
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    6. Throwing a Custom Error
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    7. Writing Unit Tests for Your Code
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
      5. Extra: Writing Tests First
    8. Tracking Test Code Coverage
      1. Problem
      2. Solution
      3. Discussion
  13. II. JavaScript in the Browser
  14. 11. Browser Tools
    1. Debugging JavaScript
      1. Problem
      2. Solution
      3. Discussion
    2. Analyzing Runtime Performance
      1. Problem
      2. Solution
      3. Discussion
    3. Identifying Unused JavaScript
      1. Problem
      2. Solution
      3. Discussion
    4. Using Lighthouse to Measure Best Practices
      1. Problem
      2. Solution
      3. Discussion
  15. 12. Working with HTML
    1. Accessing a Given Element and Finding Its Parent and Child Elements
      1. Problem
      2. Solution
      3. Discussion
    2. Traversing the Results from querySelectorAll() with forEach()
      1. Problem
      2. Solution
      3. Discussion
    3. Adding Click Functionality to an Element
      1. Problem
      2. Solution
      3. Discussion
    4. Finding All Elements That Share an Attribute
      1. Problem
      2. Solution
      3. Discussion
    5. Accessing All Elements of a Specific Type
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    6. Discovering Child Elements Using the Selectors API
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    7. Changing an Element’s Class Value
      1. Problem
      2. Solution
      3. Discussion
    8. Setting an Element’s Style Attribute
      1. Problem
      2. Solution
      3. Discussion
      4. Extra: Accessing an Existing Style Setting
      5. Advanced
    9. Adding Text to a New Paragraph
      1. Problem
      2. Solution
      3. Discussion
    10. Inserting a New Element in a Specific DOM Location
      1. Problem
      2. Solution
      3. Discussion
    11. Checking If a Checkbox Is Checked
      1. Problem
      2. Solution
      3. Discussion
    12. Adding Up Values in an HTML Table
      1. Problem
      2. Solution
      3. Discussion
      4. Extra: forEach and querySelectorAll
      5. Extra: Modularization of Globals
    13. Deleting Rows from an HTML Table
      1. Problem
      2. Solution
      3. Discussion
    14. Hiding Page Sections
      1. Problem
      2. Solution
      3. Discussion
    15. Creating Hover-Based Pop-Up Info Windows
      1. Problem
      2. Solution
      3. Discussion
    16. Validating Form Data
      1. Problem
      2. Solution
      3. Discussion
      4. Extra: HTML5 Form Validation Techniques
    17. Highlighting Form Errors and Accessibility
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    18. Creating an Accessible Automatically Updated Region
      1. Problem
      2. Solution
      3. Discussion
  16. 13. Fetching Remote Data
    1. Requesting Remote Data with Fetch
      1. Problem
      2. Solution
      3. Discussion
    2. Using XMLHttpRequest
      1. Problem
      2. Solution
      3. Discussion
    3. Submitting a Form
      1. Problem
      2. Solution
      3. Discussion
    4. Populating a Selection List from the Server
      1. Problem
      2. Solution
      3. Discussion
    5. Parsing Returned JSON
      1. Problem
      2. Solution
      3. Discussion
    6. Fetching and Parsing XML
      1. Problem
      2. Solution
      3. Discussion
    7. Sending Binary Data and Loading into an Image
      1. Problem
      2. Solution
      3. Discussion
    8. Sharing HTTP Cookies Across Domains
      1. Problem
      2. Solution
      3. Discussion
    9. Using Websockets to Establish a Two-Way Communication Between Client and Server
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    10. Long Polling a Remote Data Source
      1. Problem
      2. Solution
      3. Discussion
  17. 14. Data Persistence
    1. Persisting Information with Cookies
      1. Problem
      2. Solution
      3. Discussion
    2. Using sessionStorage for Client-Side Storage
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    3. Creating a localStorage Client-Side Data Storage Item
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    4. Persisting Larger Chunks of Data on the Client Using IndexedDB
      1. Problem
      2. Solution
      3. Discussion
    5. Simplifying IndexedDB with a Library
      1. Problem
      2. Solution
      3. Discussion
  18. 15. Working with Media
    1. Adding JavaScript to SVG
      1. Problem
      2. Solution
      3. Discussion
      4. Extra: Using SVG Libraries
    2. Accessing SVG from a Web Page Script
      1. Problem
      2. Solution
      3. Discussion
    3. Creating an SVG Bar Chart with D3
      1. Problem
      2. Solution
      3. Discussion
    4. Integrating SVG and the Canvas Element in HTML
      1. Problem
      2. Solution
      3. Discussion
      4. Extra: Canvas? Or SVG?
    5. Running a Routine When an Audio File Begins Playing
      1. Problem
      2. Solution
      3. Discussion
    6. Controlling Video from JavaScript with the video Element
      1. Problem
      2. Solution
      3. Discussion
  19. 16. Writing Web Applications
    1. Bundling JavaScript
      1. Problem
      2. Solution
      3. Discussion
      4. Extra: Using npm Modules
    2. JavaScript and the Mobile Web
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    3. Writing a Progressive Web Application
      1. Problem
      2. Solution
      3. Discussion
    4. Testing and Profiling a Progressive Web Application
      1. Problem
      2. Solution
      3. Discussion
    5. Getting the Value of the Current URL
      1. Problem
      2. Solution
      3. Discussion
    6. Redirecting a URL
      1. Problem
      2. Solution
      3. Discussion
    7. Copying Text to a User’s Clipboard
      1. Problem
      2. Solution
      3. Discussion
    8. Enabling a Mobile-Like Notification in the Desktop Browser
      1. Problem
      2. Solution
      3. Discussion
      4. Extra: Web Notifications and the Page Visibility API
    9. Loading a File Locally in the Browser
      1. Problem
      2. Solution
      3. Discussion
    10. Extending the Possible with Web Components
      1. Problem
      2. Solution
      3. Discussion
    11. Choosing a Front-End Framework
      1. Problem
      2. Solution
      3. React
      4. Vue
      5. Svelte
      6. Angular
  20. III. Node.js
  21. 17. Node Basics
    1. Managing Node Versions with Node Version Manager
      1. Problem
      2. Solution
      3. Discussion
    2. Responding to a Simple Browser Request
      1. Problem
      2. Solution
      3. Discussion
    3. Interactively Trying Out Node Code Snippets with REPL
      1. Problem
      2. Solution
      3. Discussion
      4. Extra: Wait a Second, What Global Object?
    4. Reading and Writing File Data
      1. Problem
      2. Solution
      3. Discussion
      4. Advanced
    5. Getting Input from the Terminal
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    6. Getting the Path to the Current Script
      1. Problem
      2. Solution
      3. Discussion
    7. Working with Node Timers and Understanding the Node Event Loop
      1. Problem
      2. Solution
      3. Discussion
  22. 18. Node Modules
    1. Searching for a Specific Node Module via npm
      1. Problem
      2. Solution
      3. Discussion
    2. Converting Your Library into a Node Module
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    3. Taking Your Code Across Module Environments
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
    4. Creating an Installable Node Module
      1. Problem
      2. Solution
      3. Discussion
      4. Extra: The README File and Markdown Syntax
    5. Writing Multiplatform Libraries
      1. Problem
      2. Solution
      3. Discussion
    6. Unit Testing Your Modules
      1. Problem
      2. Solution
      3. Discussion
  23. 19. Managing Node
    1. Using Environment Variables
      1. Problem
      2. Solution
      3. Discussion
    2. Managing Callback Hell
      1. Problem
      2. Solution
      3. Discussion
    3. Accessing Command-Line Functionality Within a Node Application
      1. Problem
      2. Solution
      3. Discussion
      4. Extra: Using Child Processes with Windows
    4. Passing Command-Line Arguments
      1. Problem
      2. Solution
      3. Discussion
    5. Creating a Command-Line Utility with Help from Commander
      1. Problem
      2. Solution
      3. Discussion
    6. Keeping a Node Instance Up and Running
      1. Problem
      2. Solution
      3. Discussion
    7. Monitoring Application Changes and Restarting During Local Development
      1. Problems
      2. Solution
      3. Discussion
    8. Scheduling Repeat Tasks
      1. Problem
      2. Solution
      3. Discussion
    9. Testing the Performance and Capability of Your WebSockets Application
      1. Problem
      2. Solution
      3. Discussion
  24. 20. Remote Data
    1. Fetching Remote Data
      1. Problem
      2. Solution
      3. Discussion
    2. Screen Scraping
      1. Problem
      2. Solution
      3. Discussion
    3. Accessing JSON-Formatted Data via a RESTful API
      1. Problem
      2. Solution
      3. Discussion
      4. See Also
  25. 21. Building Web Applications with Express
    1. Using Express to Respond to Requests
      1. Problem
      2. Solution
      3. Discussion
    2. Using the Express-Generator
      1. Problem
      2. Solution
      3. Discussion
    3. Routing
      1. Problem
      2. Solution
      3. Discussion
    4. Working with OAuth
      1. Problem
      2. Solution
      3. Discussion
    5. OAuth 2 User Authentication with Passport.js
      1. Problem
      2. Solution
      3. Discussion
    6. Serving Up Formatted Data
      1. Problem
      2. Solution
      3. Discussion
    7. Building a RESTful API
      1. Problem
      2. Solution
      3. Discussion
    8. Building a GraphQL API
      1. Problem
      2. Solution
      3. Discussion
  26. Index

Product information

  • Title: JavaScript Cookbook, 3rd Edition
  • Author(s): Adam D. Scott, Matthew MacDonald, Shelley Powers
  • Release date: July 2021
  • Publisher(s): O'Reilly Media, Inc.
  • ISBN: 9781492055754