Professional JavaScript
Fast-track your web development career using the powerful features of advanced JavaScript
Hugo Di Francesco
Siyuan Gao
Vinicius Isola
Philip Kirkbride
Professional JavaScript
Copyright © 2019 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the authors, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
Authors: Hugo Di Francesco, Siyuan Gao, Vinicius Isola, and Philip Kirkbride
Technical Reviewer: Archit Agarwal
Managing Editor: Aditya Shah
Acquisitions Editors: Koushik Sen and Anindya Sil
Production Editor: Shantanu Zagade
Editorial Board: Shubhopriya Banerjee, Ewan Buckingham, Mahesh Dhyani, Taabish Khan, Manasa Kumar, Alex Mazonowicz, Pramod Menon, Bridget Neale, Dominic Pereira, Shiny Poojary, Erol Staveley, Ankita Thakur, Nitesh Thakur, and Jonathan Wray
First Published: September 2019
Production Reference: 1300919
ISBN: 978-1-83882-021-3
Published by Packt Publishing Ltd.
Livery Place, 35 Livery Street
Birmingham B3 2PB, UK
Table of Contents
Preface i
Chapter 1: JavaScript, HTML, and the DOM 1
Introduction 2
HTML and the DOM 2
Exercise 1: Iterating over Nodes in a Document 4
Developer Tools 6
Exercise 2: Manipulating the DOM from the Elements Tab 9
Exercise 3: Debugging Code from the Sources Tab 12
The Console Tab 17
Activity 1: Extracting Data from a Page 20
Nodes and Elements 21
Exercise 4: Traversing the DOM Tree 24
Special Objects 29
Using JavaScript to Query the DOM 30
Exercise 5: Querying the DOM Using querySelector 32
Manipulating the DOM 37
Exercise 6: Filtering and Searching Products 42
Shadow DOM and Web Components 48
Exercise 7: Replacing a Search Box with a Web Component 58
Activity 2: Replacing the Tag Filter with a Web Component 61
Summary 62
Chapter 2: Node.js and npm 65
Introduction 66
What is Node.js? 66
Exercise 8: Running Your First Node.js Commands 71
Node Version Manager (nvm) 75
Exercise 9: Using nvm to Manage Versions 79
Node Package Manager (npm) 82
Exercise 10: Creating a Command-Line HTML Generator 87
Dependencies 91
npm Scripts 93
Activity 3: Creating an npm Package to Parse HTML 97
Summary 99
Chapter 3: Node.js APIs and Web Scraping 101
Introduction 102
Globals 102
Exercise 11: Creating a Task Reminder Application 112
FileSystem APIs 116
Exercise 12: Searching for a File through a Directory Using Glob Pattern 126
HTTP APIs 130
Exercise 13: Serving Static Files 134
Exercise 14: Serving Dynamic Content 142
What is Scraping? 148
Downloading and Parsing Web Pages 150
Exercise 15: Scraping Medium Articles 152
Activity 4: Scraping Products and Prices from Storefront 157
Summary 159
Chapter 4: RESTful APIs with Node.js 161
Introduction 162
What is an API? 162
What is REST? 164
Express.js for RESTful APIs on Node.js 164
Exercise 16: Creating an Express Project with an Index Route 165
Interacting with Your API via HTTP 167
Exercise 17: Creating and Importing a Route File 169
HTTP Status Codes 172
Designing Your API 175
Exercise 18: Creating Action Routes 178
Further Modularizing 180
Type Checking and Validating the Input Sent to an Endpoint 182
Exercise 19: Creating a Route with Type Checking and Validation 183
Useful Defaults and Easy Inputs 186
Exercise 20: Making the Duration Input Optional 186
Middleware 189
Exercise 21: Setting Up an Endpoint that Requires Authentication 191
The Contents of a JWT 196
MongoDB 197
Activity 5: Creating an API Endpoint for a Keypad Door Lock 199
Summary 200
Chapter 5: Modular JavaScript 203
Introduction 204
Dependencies and Security 205
Other Costs of Modularity 207
Reviewing Imports and Exports 208
Separation of Concerns 208
ES6 Modules 209
Exercise 22: Writing a Simple ES6 Module 210
Objects in JavaScript 212
Prototypes 212
Exercise 23: Extending the Number Prototype 215
ES6 Classes 217
Object-Oriented Programming (OOP) 218
Abstraction 219
Classes and Constructors 220
Exercise 24: Converting a Light Module to a Class 221
Default Attributes 225
Encapsulation 225
WeakMap 226
Exercise 25: WeakMap for Encapsulation 227
Getters and Setters 231
Inheritance 231
Exercise 26: Extending a Class 232
Polymorphism 235
Exercise 27: LightBulb Builder 236
npm Package 240
npm Link Command 242
Npm Publish Command 243
ESM versus CommonJS 244
Babel 244
webpack 245
Exercise 28: Converting ES6 and Packages with webpack and Babel 246
Composability and Strategies for Combining Modules 249
Activity 6: Creating a Lightbulb with a Flash Mode 250
Summary 252
Chapter 6: Code Quality 255
Introduction 256
Clear Naming 257
Convention 258
Opinionated versus Non-Opinionated 259
Linting 259
Exercise 29: Setting up ESLint and Prettier to Monitor Errors in Code 260
Unit Tests 263
Exercise 30: Setting up Jest Tests to Test a Calculator Application 265
Integration Tests 267
Exercise 31: Integration Testing with Jest 268
Code Performance Fibonacci Example 269
Exercise 32: Ensuring Performance with Jest 272
End-to-End Testing 273
Puppeteer 275
Exercise 33: End-to-End Testing with Puppeteer 277
Git Hooks 280
Exercise 34: Setting up a Local Git Hook 280
Sharing Git Hooks with Husky 282
Exercise 35: Setting up a Commit Hook with Husky 283
Exercise 36: Getting Elements by Text with Puppeteer 285
Activity 7: Putting It All Together 288
Summary 290
Chapter 7: Advanced JavaScript 293
Introduction 294
Language Features Supported in ES5, ES6, ES7, ES8, and ES9 294
Working in the Node.js REPL 295
Executing the Node.js REPL 296
Array Manipulation in JavaScript 297
Exercise 37: Creating and Modifying an Array 297
Exercise 38: Adding and Removing Items 299
Exercise 39: Getting Information About the Items in Your Array 300
Activity 8: Creating a User Tracker 302
Object Manipulation in JavaScript 302
Exercise 40: Creating and Modifying Objects in JavaScript 304
JSON.stringify 305
Exercise 41: Creating an Efficient JSON.Stringify 307
Array and Object Destructuring 309
Exercise 42: Using Destructuring Assignment for an Array 309
Exercise 43: Using Destructuring Assignment for an Object 310
Spread Operators 311
Exercise 44: Using Spread Operators 312
Rest Operators 313
OOP in JavaScript 314
Defining a Class in JavaScript 315
Exercise 45: Declaring an Object Constructor Using Functions 316
Exercise 46: Creating a Class in JavaScript 317
Creating a Simple User Information Cache Using Objects 320
Exercise 47: Creating a Cache Class to Add/Update/Remove Records from the Data Store 320
Class Inheritance 322
Exercise 48: Implementing a Subclass 322
Private and Public Methods 325
Exercise 49: Private Methods in the Vehicle Class 326
Array and Object Built-in Methods 327
Exercise 50: Using Iteration Methods on Arrays 330
Exercise 51: Lookups and Filtering the Array 332
Sorting 334
Exercise 52: Sorting Arrays in JavaScript 335
Array Reduce 338
Exercise 53: Using JavaScript Reduce Method to Make Calculations for a Shopping Cart 338
Activity 9: Creating a Student Manager Using JavaScript Arrays and Classes 340
Maps and Sets 342
Exercise 54: Using Maps versus Objects 342
Exercise 55: Using Sets to Track Unique Values 345
Math, Date, and String 347
Exercise 56: Using String Methods 348
Math and Date 350
Exercise 57: Using Math and Date 350
Symbols, Iterators, Generators, and Proxies 353
Symbol 353
Iterator and Generator 354
Exercise 58: Using Symbols and Exploring Their Properties 354
Exercise 59: Iterators and Generators 356
Proxies 358
Exercise 60: Using Proxies to Build Complex Objects 360
Refactoring in JavaScript 362
Activity 10: Refactoring Functions to Use Modern JavaScript Features 363
Summary 364
Chapter 8: Asynchronous Programming 367
Introduction 368
How JavaScript Handles Time-Consuming Operations 370
Handling Async Operations Using Callbacks 371
Exercise 61: Writing Your First Callback 371
Event Loops 376
How JavaScript Executes Code 377
Activity 11: Using Callbacks to Receive Results 379
Callback Hell 381
Promises 384
Exercise 62: Using Promises as Alternatives to Callbacks 385
Chaining Promises 389
Exercise 63: Advanced JavaScript Promises 392
Error Handling in Promises 398
Exercise 64: Refactor the Bill Calculator Using Promises 403
Async and Await 407
Exercise 65: Async and Await Functions 409
Async Await Concurrency 415
When to Use await 418
Exercise 66: Complex Async Implementation 420
Activity 12: Refactor the Bill Calculator Using Async and Await 426
Migrating Callback- and Promise-Based Code to Async and Await 428
Migrating Callback-Based Code to Async and Await 428
Summary 430
Chapter 9: Event-Driven Programming and Built-In Modules 433
Introduction 434
The Traditional Approach versus Event-Driven Programming 435
Eventing 437
Exercise 67: A Simple Event Emitter 439
EventEmitter Methods 442
Removing Listeners 442
Removing all Listeners 443
Attaching a One-Time Listener 444
Reading from Event Emitters 446
Getting a List of Events That Have Listeners Registered 448
Max Listeners 448
Prepend Listeners 449
Concurrency in Listeners 450
Building Custom Event Emitters 452
Exercise 68: Building A Chatroom Application 456
Activity 13: Building an Event-Driven Module 462
Event-Driven Programming Best Practices 463
Node.js Built-In Modules 468
path 468
fs 470
Exercise 69: Basic Usage of the Fs Module 474
Handling Large Files in Node.js 478
Util 479
Timer 481
Activity 14: Building a File Watcher 486
Summary 487
Chapter 10: Functional Programming with JavaScript 489
Introduction 490
Functions – First-Class Citizens 490
First-Class Functions – Idiomatic JavaScript Building Blocks 490
Inversion of Control Using First-Class Functions 492
Functions that Enable Asynchronous I/O and Event-Driven Programming in JavaScript 493
JavaScript Built-In Array Methods that Showcase First-Class Function Support 496
Exercise 70: Re-Implementing includes, indexOf, and join with some, findIndex, and reduce 499
Exercise 71: Computing the Price of a Basket Using Map and Reduce 502
Child-Parent Component Communication in React 504
Activity 15: onCheckout Callback Prop 509
Exercise 72: Adding a Product to the Basket 510
First-Class Functions in React Render Props 512
Exercise 73: Rendering Basket Contents with a Render Prop 514
Pure Functions 517
Redux Reducers and Actions 518
Exercise 74: Redux Dispatching Actions and Reducing Them into State 520
Testing Pure Functions 524
Exercise 75: Testing a Reducer 525
Redux Selectors 529
Exercise 76: Implementing a Selector 529
Activity 16: Testing a Selector 532
Higher-Order Functions 532
bind, apply, and call 533
Currying and Partial Application 537
Leveraging Closures React Function Components 539
Function Composition 540
Exercise 77: A Binary to n-ary Compose Function 542
Function Composition in the Real World with a Simple BFF 544
Exercise 78: Leveraging Compose to Simplify the Micro Server Creation Step 547
Immutability and Side Effects 551
A Look at Redux Action Creators 551
Exercise 79: Refactoring the React/Redux Application to Use Action Creators 552
React-Redux mapStateToProps and mapDispatchToProps 555
Exercise 80: Abstracting State Management Using the mapDispatchToProps Function 556
Redux Reducers In Depth 559
Changing JavaScript-Native Methods to an Immutable Functional Style 560
Handling Side Effects in a React/Redux Application React Life Cycle Hooks 566
Handling Side Effects in a React/Redux Application React Hooks 567
Handling Side Effects in a React/Redux Application Redux-Thunk 568
Introduction to GraphQL Language Schemas and Queries 570
Running Updates with GraphQL Mutations and Resolvers 572
Exercise 81: Implementing a BFF Mutation with micro and GraphQL 573
Activity 17: Fetching the Current Basket From BFF 577
Summary 578
Appendix 581
Preface
About
This section briefly introduces the authors, the coverage of this book, the technical skills you'll need to get started, and the hardware and software requirements required to complete all of the included activities and exercises.
Chapter 1
JavaScript, HTML, and the DOM
Learning Objectives
By the end of this chapter, you will be able to:
Describe the HTML Document Object Model (DOM)Use the Chrome DevTools source tab to explore the DOM of a web pageImplement JavaScript to query and manipulate the DOMBuild custom components using Shadow DOM
In this chapter, we will learn about the DOM and how to interact with and manipulate it using JavaScript. We will also learn how to build dynamic applications using reusable custom components.