This document was uploaded by user and they confirmed that they have the permission to share
it. If you are author or own the copyright of this book, please report to us by using this DMCA
report form. Report DMCA
Overview
Download & View Professional Javascript as PDF for free.
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
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
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
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
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
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
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
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
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
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
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.
ii | Preface
About the Book In depth knowledge of JavaScript makes it easier to learn a variety of other frameworks, including React, Angular, and related tools and libraries. This book is designed to help you cover the core JavaScript concepts you need to build modern applications. You'll start by learning how to represent an HTML document in the Document Object Model (DOM). Then, you'll combine your knowledge of the DOM and Node.js to create a web scraper for practical situations. As you read through further chapters, you'll create a Node.js-based RESTful API using the Express library for Node.js. You'll also understand how modular designs can be used for better reusability and collaboration with multiple developers on a single project. Later chapters will guide you through building unit tests, which ensure that the core functionality of your program is not affected over time. The book will also demonstrate how constructors, async/await, and events can load your applications quickly and efficiently. Finally, you'll gain useful insights into functional programming concepts such as immutability, pure functions, and higher-order functions. By the end of this book, you'll have the skills you need to tackle any real-world JavaScript development problem using a modern JavaScript approach, both for the client and server sides.
About the Authors Hugo Di Francesco is a software engineer who has worked extensively with JavaScript. He holds a MEng degree in mathematical computation from University College London (UCL). He has used JavaScript across the stack to create scalable and performant platforms at companies such as Canon and Elsevier. He is currently tackling problems in the retail operations space with Node.js, React, and Kubernetes while running the eponymous Code with Hugo website. Outside of work, he is an international fencer, in the pursuit of which he trains and competes across the globe. Siyuan Gao is a software engineer at Electronic Arts. He has a bachelor's degree in computer science from Purdue University. He has worked with JavaScript and Node.js for over 4 years, mainly building efficient backend solutions for high-availability systems. He is also a contributor to the Node.js Core project and has had many npm modules published. In his spare time, he enjoys learning about video game design and machine learning. Vinicius Isola started programming back in 1999 using Macromedia Flash and ActionScript. In 2005, he took the Java Certification and specialized in building web and enterprise applications. Always working on all parts of the stack, JavaScript and web technologies have always been present in his many job roles and the companies he has worked for. In his free time, he likes to work on open-source projects and mentor new developers.
About the Book | iii Philip Kirkbride has over 5 years of experience with JavaScript and is based in Montreal. He graduated from a technical college in 2011 and since then he has been working with web technologies in various roles. He worked with 2Klic, an IoT company contracted by the major electrical heating company Convectair to create smart heaters powered by Z-Wave technology. His role consisted of writing microservices in Node. js and Bash. He has also had a chance to make some contributions to the open-source projects SteemIt (a blockchain-based blogging platform) and DuckDuckGo (a privacy-based search engine).
Learning Objectives By the end of this book, you will be able to: • Apply the core concepts of functional programming • Build a Node.js project that uses the Express.js library to host an API • Create unit tests for a Node.js project to validate it • Use the Cheerio library with Node.js to create a basic web scraper • Develop a React interface to build processing flows • Use callbacks as a basic way to bring control back
Audience If you want to advance from being a frontend developer to a full-stack developer and learn how Node.js can be used for hosting full-stack applications, this is an ideal book for you. After reading this book, you'll be able to write better JavaScript code and learn about the latest trends in the language. To easily grasp the concepts explained here, you should know the basic syntax of JavaScript and should've worked with popular frontend libraries such as jQuery. You should have also used JavaScript with HTML and CSS but not necessarily Node.js.
Approach Each section of this book has been explicitly designed to engage and stimulate you so that you can retain and apply what you learn in a practical context with maximum impact. You'll learn how to tackle intellectually stimulating programming challenges that will prepare you for real-world topics through functional programming and testdriven development practices. Each chapter has been explicitly designed to build upon JavaScript as a core language.
iv | Preface
Hardware Requirements For the optimal experience, we recommend the following hardware configuration: • Processor: Intel Core i5 or equivalent • Memory: 4 GB of RAM • Storage: 5 GB of available space
Software Requirements We also recommend that you have the following software installed in advance: • Git latest version • Node.js 10.16.3 LTS (https://nodejs.org/en/)
Conventions Code words in the text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "The ES6 import function also allows you to import a subsection of a module, rather than importing the whole thing. This is one capability ES6's import has over the Node.js require function. SUSE" A block of code is set as follows: let myString = "hello"; console.log(myString.toUpperCase()); // returns HELLO console.log(myString.length); // returns 5
Installation and Setup Before we can do awesome things with data, we need to be prepared with the most productive environment. In this short section, we will see how to do that.
Installing Node.js and npm Installations of Node.js come with npm (Node.js's default package manager) included. Installing Node.js on Windows: 1. Find your desired version of Node.js on the official installation page at https:// nodejs.org/en/download/current/. 2. Ensure you select Node.js 12 (the current version).
About the Book | v 3. Ensure that you install the correct architecture for your computer system; that is, either 32-bit or 64-bit. You can find out this information in the System Properties window of your OS. 4. After you download the installer, simply double-click on the file and follow the user-friendly prompts on-screen. Installing Node.js and npm on Linux: To install Node.js on Linux, you have a few good options: • To install Node.js through Linux package managers on systems not detailed below, see https://nodejs.org/en/download/package-manager/. • To install Node.js on Ubuntu, run this (more information and manual installation instructions can be found at https://github.com/nodesource/distributions/blob/ master/README.md#installation-instructions): curl -sL https://deb.nodesource.com/setup_12.x | sudo -E bash sudo apt-get install -y nodejs • To install Node.js on Debian-based distributions (more information and manual installation instructions can be found at https://github.com/nodesource/distributions/blob/master/README.md#installation-instructions): # As root curl -sL https://deb.nodesource.com/setup_12.x | bash apt-get install -y nodejs • The official Node.js installation page has further installation options for some Linux systems: https://nodejs.org/en/download/current/. Installing Node.js and npm on macOS: Similar to Linux, you have a couple of methods for installing Node.js and npm on a Mac. To install Node.js and npm on macOS X, do the following: 1. Open Terminal for Mac by pressing cmd + Spacebar, typing terminal in the open search box, and hitting Enter. 2. Install Xcode through the command line by running xcode-select --install. 3. The easiest way to install Node.js and npm is using Homebrew, which is installed through the command line by running ruby -e "$(curl -fsSL (https://raw. githubusercontent.com/Homebrew/install/master/install).
vi | Preface 4. The final step is to install Node.js and npm. On the command line, run brew install node. 5. Again, you can also install Node.js and npm via the installer available at https:// nodejs.org/en/download/current/. Installing Git To install git go to https://git-scm.com/downloads and follow instructions specific to your platform.
Additional Resources The code bundle for this book is also hosted on GitHub at https://github.com/ TrainingByPackt/Professional-JavaScript. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
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 page • Implement JavaScript to query and manipulate the DOM • Build 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.
2 | JavaScript, HTML, and the DOM
Introduction HTML started as a markup language for static documents that was easy to use and could be written using any text editor. After JavaScript became a major player in the internet world, there was a need to expose the HTML documents to the JavaScript runtime. That's when the DOM, was created. The DOM is HTML mapped to a tree of objects that can be queried and manipulated using JavaScript. In this chapter, you'll learn what the DOM is and how to use JavaScript to interact with it. You'll learn how to find elements and data in a document, how to manipulate elements states, and how to modify their content. You'll also learn how to create DOM elements and append them to a page. After learning about the DOM and how to manipulate it, you'll build a dynamic application using some sample data. Lastly, you'll learn how to create custom HTML elements to build reusable components using Shadow DOM.
HTML and the DOM When a browser loads an HTML page, it creates a tree that represents that page. This tree is based on the DOM specification. It uses tags to determine where each node starts and ends. Consider the following piece of HTML code: Sample Page
This is a paragraph.
This is a paragraph inside a div.
HTML and the DOM | 3 The browser will create the following hierarchy of nodes:
Figure 1.1: A paragraph node contains a text node
Everything becomes a node. Texts, elements, and comments, all the way up to the root of the tree. This tree is used to match styles from CSS and render the page. It's also transformed into an object and made available to the JavaScript runtime.
4 | JavaScript, HTML, and the DOM But why is it called the DOM? Because HTML was originally designed to share documents and not to design the rich dynamic applications we have today. That means that every HTML DOM starts with a document element, to which all elements are attached. With that in mind, the previous illustration of the DOM tree actually becomes the following:
Figure 1.2: All DOM trees have a document element at the root
What does it mean when I say that the browser makes the DOM available to the JavaScript runtime? It means that if you write some JavaScript code in your HTML page, you can access that tree and do some pretty interesting things with it. For example, you can easily access the document root element and access all of the nodes on a page, which is what you're going to do in the next exercise.
Exercise 1: Iterating over Nodes in a Document In this exercise, we'll write JavaScript code to query the DOM to find a button and add an event listener to it so that we can execute some code when the user clicks on it. When the event happens, we'll query for all paragraph elements, count and store their content, then show an alert at the end. The code files for this exercise can be found at https://github.com/TrainingByPackt/ Professional-JavaScript/tree/master/Lesson01/Exercise01. Perform the following steps to complete the exercise: 1. Open the text editor of your preference and create a new file called alert_paragraphs.html containing the sample HTML from the previous section (which can be found on GitHub: https://bit.ly/2maW0Sx): Sample Page
HTML and the DOM | 5
This is a paragraph.
This is a paragraph inside a div.
2. At the end of the body element, add a script tag such that the last few lines look like the following: