JavaScript Cookbook, 3rd Edition (Adam D. Scott, Matthew MacDonald etc.) (Z-Library)

Author: Adam D. Scott, Matthew MacDonald, Shelley Powers

JavaScript

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

📄 File Format: PDF
💾 File Size: 9.1 MB
44
Views
0
Downloads
0.00
Total Donations

📄 Text Preview (First 20 pages)

ℹ️

Registered users can read the full content for free

Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.

📄 Page 1
Third Edition JavaScript Cookbook Programming the Web Adam D. Scott, Matthew MacDonald & Shelley Powers
📄 Page 2
(This page has no text content)
📄 Page 3
Adam D. Scott, Matthew MacDonald, and Shelley Powers JavaScript Cookbook THIRD EDITION
📄 Page 4
978-1-492-05575-4 [LSI] JavaScript Cookbook, Third Edition by Adam D. Scott, Matthew MacDonald, and Shelley Powers Copyright © 2021 Adam D. Scott and Matthew MacDonald. 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 promotional use. Online editions are also available for most titles (http://oreilly.com). For more information, contact our corporate/institutional sales department: 800-998-9938 or corporate@oreilly.com. Acquisitions Editor: Jennifer Pollock Development Editor: Angela Rufino Production Editor: Katherine Tozer Copyeditor: Sonia Saruba Proofreader: James Fraleigh Indexer: Potomac Indexing, LLC Interior Designer: David Futato Cover Designer: Karen Montgomery Illustrator: Kate Dullea July 2021: Third Edition Revision History for the Third Edition 2021-07-16: First Release See http://oreilly.com/catalog/errata.csp?isbn=9781492055754 for release details. The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. JavaScript Cookbook, the cover image, and related trade dress are trademarks of O’Reilly Media, Inc. The views expressed in this work are those of the authors, and do not represent the publisher’s views. While the publisher and the authors have used good faith efforts to ensure that the information and instructions contained in this work are accurate, the publisher and the authors disclaim all responsibility for errors or omissions, including without limitation responsibility for damages resulting from the use of or reliance on this work. Use of the information and instructions contained in this work is at your own risk. If any code samples or other technology this work contains or describes is subject to open source licenses or the intellectual property rights of others, it is your responsibility to ensure that your use thereof complies with such licenses and/or rights.
📄 Page 5
Table of Contents Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xi Part I. The JavaScript Language 1. Setting Up a Development Environment. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 1.1 Choosing a Code Editor 2 1.2 Using the Developer Console in Your Browser 3 1.3 Running Blocks of Code in the Developer Console 7 1.4 Using Strict Mode to Catch Common Mistakes 9 1.5 Filling in HTML Boilerplate with Emmet Shortcuts 11 1.6 Installing the npm Package Manager (with Node.js) 13 1.7 Downloading a Package with npm 16 1.8 Updating a Package with npm 20 1.9 Setting Up a Local Test Server 21 1.10 Enforcing Code Standards with a Linter 24 1.11 Styling Code Consistently with a Formatter 28 1.12 Experimenting in a JavaScript Playground 31 2. Strings and Regular Expressions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35 2.1 Checking for an Existing, Nonempty String 35 2.2 Converting a Numeric Value to a Formatted String 38 2.3 Inserting Special Characters 40 2.4 Inserting Emojis 42 2.5 Using Template Literals for Clearer String Concatenation 43 2.6 Performing a Case-Insensitive String Comparison 45 2.7 Checking If a String Contains a Specific Substring 46 2.8 Replacing All Occurrences of a String 47 iii
📄 Page 6
2.9 Replacing HTML Tags with Named Entities 48 2.10 Using a Regular Expression to Replace Patterns in a String 49 2.11 Extracting a List from a String 52 2.12 Finding All Instances of a Pattern 54 2.13 Removing Whitespace from the Beginning and End of a String 57 2.14 Converting the First Letter of a String to Uppercase 58 2.15 Validating an Email Address 59 3. Numbers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61 3.1 Generating Random Numbers 61 3.2 Generating Cryptographically Secure Random Numbers 63 3.3 Rounding to a Specific Decimal Place 65 3.4 Preserving Accuracy in Decimal Values 66 3.5 Converting a String to a Number 68 3.6 Converting a Decimal to a Hexadecimal Value 70 3.7 Converting Between Degrees and Radians 71 3.8 Calculating the Length of a Circular Arc 71 3.9 Manipulating Very Large Numbers with BigInt 72 4. Dates. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75 4.1 Getting the Current Date and Time 75 4.2 Converting a String to a Date 77 4.3 Adding Days to a Date 79 4.4 Comparing Dates and Testing Dates for Equality 80 4.5 Calculating the Time Elapsed Between Two Dates 82 4.6 Formatting a Date Value as a String 84 5. Arrays. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87 5.1 Checking If an Object Is an Array 88 5.2 Iterating Over All the Elements in an Array 88 5.3 Checking If Two Arrays Are Equal 90 5.4 Breaking Down an Array into Separate Variables 93 5.5 Passing an Array to a Function That Expects a List of Values 94 5.6 Cloning an Array 95 5.7 Merging Two Arrays 97 5.8 Copying a Portion of an Array by Position 98 5.9 Extracting Array Items That Meet Specific Criteria 100 5.10 Emptying an Array 101 5.11 Removing Duplicate Values 102 5.12 Flattening a Two-Dimensional Array 103 5.13 Searching Through an Array for Exact Matches 104 5.14 Searching Through an Array for Items That Meet Specific Criteria 105 iv | Table of Contents
📄 Page 7
5.15 Removing or Replacing Array Elements 107 5.16 Sorting an Array of Objects by a Property Value 108 5.17 Transforming Every Element of an Array 109 5.18 Combining an Array’s Values in a Single Calculation 110 5.19 Validating Array Contents 112 5.20 Creating a Collection of Nonduplicated Values 113 5.21 Creating a Key-Indexed Collection of Items 114 6. Functions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117 6.1 Passing a Function as an Argument to Another Function 117 6.2 Using Arrow Functions 121 6.3 Providing a Default Parameter Value 124 6.4 Creating a Function That Accepts Unlimited Arguments 125 6.5 Using Named Function Parameters 126 6.6 Creating a Function That Stores its State with a Closure 129 6.7 Creating a Generator Function That Yields Multiple Values 131 6.8 Reducing Redundancy by Using Partial Application 135 6.9 Fixing this with Function Binding 138 6.10 Implementing a Recursive Algorithm 141 7. Objects. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145 7.1 Checking if an Object Is a Certain Type 145 7.2 Using an Object Literal to Bundle Data 147 7.3 Checking If an Object Has a Property 150 7.4 Iterating Over All the Properties of an Object 152 7.5 Testing for an Empty Object 154 7.6 Merging the Properties of Two Objects 155 7.7 Customizing the Way a Property Is Defined 156 7.8 Preventing Any Changes to an Object 159 7.9 Intercepting and Changing Actions on an Object with a Proxy 161 7.10 Cloning an Object 164 7.11 Making a Deep Copy of an Object 166 7.12 Creating Absolutely Unique Object Property Keys 168 7.13 Creating Enums with Symbol 170 8. Classes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173 8.1 Creating a Reusable Class 173 8.2 Adding Properties to a Class 177 8.3 Giving a Class a Better String Representation 182 8.4 Using the Constructor Pattern to Make a Custom Class 183 8.5 Supporting Method Chaining in Your Class 186 8.6 Adding Static Methods to a Class 188 Table of Contents | v
📄 Page 8
8.7 Using a Static Method to Create Objects 190 8.8 Inheriting Functionality from Another Class 192 8.9 Organizing Your JavaScript Classes with Modules 197 9. Asynchronous Programming. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201 9.1 Updating the Page During a Loop 202 9.2 Using a Function That Returns a Promise 204 9.3 Promisifying an Asynchronous Function That Uses a Callback 208 9.4 Executing Multiple Promises Concurrently 211 9.5 Waiting for a Promise to Finish with Await and Async 214 9.6 Creating an Asynchronous Generator Function 218 9.7 Using a Web Worker to Perform a Background Task 220 9.8 Adding Progress Support to a Web Worker 224 10. Errors and Testing. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227 10.1 Catching and Neutralizing an Error 227 10.2 Catching Different Types of Errors 230 10.3 Catching Asynchronous Errors 232 10.4 Detecting Unhandled Errors 233 10.5 Throwing a Standard Error 237 10.6 Throwing a Custom Error 239 10.7 Writing Unit Tests for Your Code 241 10.8 Tracking Test Code Coverage 247 Part II. JavaScript in the Browser 11. Browser Tools. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253 11.1 Debugging JavaScript 253 11.2 Analyzing Runtime Performance 255 11.3 Identifying Unused JavaScript 257 11.4 Using Lighthouse to Measure Best Practices 259 12. Working with HTML. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263 12.1 Accessing a Given Element and Finding Its Parent and Child Elements 263 12.2 Traversing the Results from querySelectorAll() with forEach() 266 12.3 Adding Click Functionality to an Element 267 12.4 Finding All Elements That Share an Attribute 269 12.5 Accessing All Elements of a Specific Type 269 12.6 Discovering Child Elements Using the Selectors API 272 12.7 Changing an Element’s Class Value 273 12.8 Setting an Element’s Style Attribute 274 vi | Table of Contents
📄 Page 9
12.9 Adding Text to a New Paragraph 276 12.10 Inserting a New Element in a Specific DOM Location 278 12.11 Checking If a Checkbox Is Checked 279 12.12 Adding Up Values in an HTML Table 280 12.13 Deleting Rows from an HTML Table 283 12.14 Hiding Page Sections 285 12.15 Creating Hover-Based Pop-Up Info Windows 287 12.16 Validating Form Data 289 12.17 Highlighting Form Errors and Accessibility 292 12.18 Creating an Accessible Automatically Updated Region 298 13. Fetching Remote Data. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 301 13.1 Requesting Remote Data with Fetch 301 13.2 Using XMLHttpRequest 305 13.3 Submitting a Form 306 13.4 Populating a Selection List from the Server 310 13.5 Parsing Returned JSON 314 13.6 Fetching and Parsing XML 316 13.7 Sending Binary Data and Loading into an Image 318 13.8 Sharing HTTP Cookies Across Domains 319 13.9 Using Websockets to Establish a Two-Way Communication Between Client and Server 320 13.10 Long Polling a Remote Data Source 322 14. Data Persistence. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 325 14.1 Persisting Information with Cookies 325 14.2 Using sessionStorage for Client-Side Storage 328 14.3 Creating a localStorage Client-Side Data Storage Item 334 14.4 Persisting Larger Chunks of Data on the Client Using IndexedDB 338 14.5 Simplifying IndexedDB with a Library 341 15. Working with Media. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 345 15.1 Adding JavaScript to SVG 345 15.2 Accessing SVG from a Web Page Script 348 15.3 Creating an SVG Bar Chart with D3 350 15.4 Integrating SVG and the Canvas Element in HTML 354 15.5 Running a Routine When an Audio File Begins Playing 356 15.6 Controlling Video from JavaScript with the video Element 357 16. Writing Web Applications. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 361 16.1 Bundling JavaScript 361 16.2 JavaScript and the Mobile Web 363 Table of Contents | vii
📄 Page 10
16.3 Writing a Progressive Web Application 366 16.4 Testing and Profiling a Progressive Web Application 373 16.5 Getting the Value of the Current URL 377 16.6 Redirecting a URL 379 16.7 Copying Text to a User’s Clipboard 380 16.8 Enabling a Mobile-Like Notification in the Desktop Browser 382 16.9 Loading a File Locally in the Browser 385 16.10 Extending the Possible with Web Components 388 16.11 Choosing a Front-End Framework 391 Part III. Node.js 17. Node Basics. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 397 17.1 Managing Node Versions with Node Version Manager 397 17.2 Responding to a Simple Browser Request 400 17.3 Interactively Trying Out Node Code Snippets with REPL 402 17.4 Reading and Writing File Data 405 17.5 Getting Input from the Terminal 410 17.6 Getting the Path to the Current Script 412 17.7 Working with Node Timers and Understanding the Node Event Loop 413 18. Node Modules. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 419 18.1 Searching for a Specific Node Module via npm 420 18.2 Converting Your Library into a Node Module 421 18.3 Taking Your Code Across Module Environments 422 18.4 Creating an Installable Node Module 425 18.5 Writing Multiplatform Libraries 431 18.6 Unit Testing Your Modules 435 19. Managing Node. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 439 19.1 Using Environment Variables 439 19.2 Managing Callback Hell 441 19.3 Accessing Command-Line Functionality Within a Node Application 444 19.4 Passing Command-Line Arguments 447 19.5 Creating a Command-Line Utility with Help from Commander 448 19.6 Keeping a Node Instance Up and Running 450 19.7 Monitoring Application Changes and Restarting During Local Development 452 19.8 Scheduling Repeat Tasks 453 19.9 Testing the Performance and Capability of Your WebSockets Application 455 viii | Table of Contents
📄 Page 11
20. Remote Data. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 457 20.1 Fetching Remote Data 457 20.2 Screen Scraping 459 20.3 Accessing JSON-Formatted Data via a RESTful API 461 21. Building Web Applications with Express. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 465 21.1 Using Express to Respond to Requests 465 21.2 Using the Express-Generator 469 21.3 Routing 474 21.4 Working with OAuth 476 21.5 OAuth 2 User Authentication with Passport.js 486 21.6 Serving Up Formatted Data 491 21.7 Building a RESTful API 492 21.8 Building a GraphQL API 496 Index. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 501 Table of Contents | ix
📄 Page 12
(This page has no text content)
📄 Page 13
Preface As I sat down to work on the latest edition of JavaScript Cookbook, I considered the “cookbook” metaphor carefully. What makes a great food cookbook? Browsing the cookbooks on a shelf in my dining room, I noted that my favorites not only have deli‐ cious recipes, but they are also full of opinionated hard-earned advice. A cookbook rarely seeks to teach you every recipe for beef bourguignon; rather it teaches you the technique and recipe that the author has found works best for them, typically with a bit of advice thrown in for good measure. It’s with this concept in mind that we put together this collection of JavaScript recipes. The advice in this book comes from three seasoned pros, but it is ultimately the culmination of our unique experiences. Any other group of developers would have likely produced a similar, but different book. JavaScript has developed into an amazing and powerful multipurpose programming language. With this collection in hand you will be able to solve all sorts of problems that you encounter and may even begin to develop recipes of your own. Book Audience To encompass the many subjects and topics reflective of JavaScript in use today, we had to start with one premise: this is not a book for someone brand new to program‐ ming. There are so many good books and tutorials for those looking to learn to pro‐ gram with JavaScript that we felt comfortable targeting the practicing developer, some‐ one looking to solve specific problems and challenges with JavaScript. If you’ve been playing around with JavaScript for several months, maybe tried your hand with a little Node or web development, you should be comfortable with the book material. Additionally, if you’re a developer who primarily works in another programming language, but find yourself needing to use JavaScript from time to time, this should be a helpful guide. Finally, if you’re a working JavaScript developer who sometimes gets stuck on some of the idiosyncrasies of the language, this should act as a useful resource. xi
📄 Page 14
Book Organization There are two types of readers of this book. The first is someone who reads it cover to cover, picking up tidbits of applicable knowledge along the way. The second is some‐ one who dips their toes in as needed, seeking out the solution to a specific challenge or category of problem that they face. We attempted to organize the book in such a way that it would be useful to both types of readers, organizing it into three sections: • Part I, The JavaScript Language, covers recipes for JavaScript as a programming language. • Part II, JavaScript in the Browser, covers JavaScript in its natural habitat: the browser. • Part III, Node.js, looks at JavaScript specifically through the lens of Node.js. Each chapter of the book is broken down into several individual “recipes.” A recipe is composed of several parts: Problem This defines a common development scenario where JavaScript may be used. Solution A solution to the problem, with a code sample and minimal description. Discussion An in-depth discussion of the code sample and techniques. Additionally, a recipe may contain recommendations for further reading in a “See Also” section, or additional techniques in an “Extra” section. Conventions Used in This Book The following typographical conventions are used in this book: Italic Indicates new terms, URLs, email addresses, filenames, and file extensions. Bold Indicates UI items such as menu items and buttons to be selected or clicked. Constant width Indicates computer code in a broad sense, including commands, arrays, elements, statements, options, switches, variables, attributes, keys, functions, types, classes, namespaces, methods, modules, properties, parameters, values, objects, events, event handlers, XML tags, HTML tags, macros, the contents of files, and the output from commands. xii | Preface
📄 Page 15
Constant width bold Shows commands or other text that should be typed literally by the user. Constant width italic hows text that should be replaced with user-supplied values or by values determined by context. This element signifies a general note. This element signifies a tip or suggestion. This element indicates a warning or caution. Websites and pages are mentioned in this book to help you locate online information that might be useful. Normally both the address (URL) and the name (or title, or appropriate heading) of a page are mentioned. Some addresses are relatively compli‐ cated. You may locate such pages more easily using your favorite search engine to search for a page by its name. This may also help if the page cannot be found by its address; the URL may have changed, but the name may still work. Using Code Examples Supplemental material (code examples, exercises, etc.) is available for download at https://github.com/javascripteverywhere/cookbook. This book is here to help you get your job done. In general, if example code is offered with this book, you may use it in your programs and documentation. You do not need to contact us for permission unless you’re reproducing a significant portion of the code. For example, writing a program that uses several chunks of code from this book does not require permission. Selling or distributing examples from O’Reilly books does require permission. Answering a question by citing this book and quoting example code does not require permission. Incorporating a significant amount of example code from this book into your product’s documentation does require permission. Preface | xiii
📄 Page 16
We appreciate, but do not require, attribution. An attribution usually includes the title, author, publisher, and ISBN. For example: JavaScript Cookbook, Third Edition, by Adam D. Scott, Matthew MacDonald, and Shelley Powers. Copyright 2021 Adam D. Scott and Matthew MacDonald, 978-1-492-05575-4. If you feel your use of code examples falls outside fair use or the permission given here, feel free to contact us at permissions@oreilly.com. O’Reilly Online Learning For more than 40 years, O’Reilly Media has provided technol‐ ogy and business training, knowledge, and insight to help companies succeed. Our unique network of experts and innovators share their knowledge and expertise through books, articles, and our online learning platform. O’Reilly’s online learning platform gives you on-demand access to live training courses, in-depth learning paths, interactive coding environments, and a vast collection of text and video from O’Reilly and 200+ other publishers. For more information, visit http://oreilly.com. How to Contact Us Please address comments and questions concerning this book to the publisher: O’Reilly Media, Inc. 1005 Gravenstein Highway North Sebastopol, CA 95472 800-998-9938 (in the United States or Canada) 707-829-0515 (international or local) 707-829-0104 (fax) We have a web page for this book, where we list errata, examples, and any additional information. You can access this page at https://oreil.ly/js-cookbook-3e. Email bookquestions@oreilly.com to comment or ask technical questions about this book. For news and information about our books and courses, visit http://oreilly.com. Find us on Facebook: http://facebook.com/oreilly Follow us on Twitter: http://twitter.com/oreillymedia Watch us on YouTube: http://www.youtube.com/oreillymedia xiv | Preface
📄 Page 17
Acknowledgments This is the third edition of the JavaScript Cookbook. The first two editions were writ‐ ten by Shelley Powers. This edition was written and updated by Adam Scott and Mat‐ thew MacDonald. Adam and Matthew would like to thank their editors, Angela Rufino and Jennifer Pollock, who shepherded the project through all its growing pains; and their top-shelf tech reviewers, Sarah Wachs, Schalk Neethling, and Elisa‐ beth Robson, who offered many sharp insights and helpful suggestions. Adam would also like to thank John Paxton for his support and conversation during the early drafts of this edition. Shelley thanks her editors, Simon St. Laurent and Brian McDonald, and her tech reviewers, Dr. Axel Rauschmayer and Semmy Purewal. Collectively we all thank the O’Reilly production staff for their ongoing help and support. Preface | xv
📄 Page 18
(This page has no text content)
📄 Page 19
PART I The JavaScript Language
📄 Page 20
(This page has no text content)
The above is a preview of the first 20 pages. Register to read the complete e-book.

💝 Support Author

0.00
Total Amount (¥)
0
Donation Count

Login to support the author

Login Now
Back to List