Professional Javascript? for Web Developers, First by Matt Frisbie

PROFESSIONAL
JavaScript® for Web Developers

 

Matt Frisbie

 

 

 

 

 

 

 

 

Wiley Logo

To Jordan, for her unwavering support no matter how many times she heard “it's almost done.”

ABOUT THE AUTHOR

MATT FRISBIE has worked in web development for over a decade. During that time, he's been a startup co-founder, an engineer at a Big Four tech company, and the first engineer at a Y Combinator startup that would eventually become a billion-dollar business. As a Google software engineer, Matt worked on both the AdSense and Accelerated Mobile Pages (AMP) platforms; his code contributions run on most of the planet's web browsing devices. Prior to this, Matt was the first engineer at DoorDash, where he laid the foundation for their driver scheduling, menu management, and order dispatch infrastructure. Matt has written two books and recorded two video series for O'Reilly and Packt, speaks at frontend meetups and webcasts, and is a Level 1 sommelier. He majored in computer engineering at the University of Illinois at Urbana–Champaign. Matt's Twitter handle is @mattfriz.

ABOUT THE TECHNICAL EDITORS

CHAIM KRAUSE is a lover of computers, electronics, animals, and electronic music. He's tickled pink when he can combine two or more of these interests in one project. The vast majority of his knowledge is through self-learning. He jokes with everyone that the only difference between what he does at home and what he does at work is the logon he uses. As a lifelong learner, he is often frustrated with technical errors in documentation that waste valuable time and cause unnecessary frustration. One of the reasons he works as a technical editor on technology books is to help others avoid those same pitfalls.

MARCIA WILBUR is a technical communicator, consulting in the semiconductor field, focusing on Industrial IoT (IIoT) and AI. Marcia holds degrees in computer science, technical communication, and information technology. As Copper Linux User Group president, she is heavily involved with the maker community, leading West Side Linux + Pi, and the East Valley, leading regular Raspberry Pi, Beaglebone, Banana Pi/Pro, and ESP8266 projects. These projects include home automation, gaming consoles, surveillance, network, multimedia, and other “pi fun.”

In addition to tinkering, she volunteers for different organizations using Pi units and Linux to provide access to educational content for K–12 schools in rural, underserved, and disaster-stricken areas. For fun, she serves the community as the lead Debian developer for Linux Respin, a backup and distro customization tool.

ACKNOWLEDGMENTS

THANKS TO WILEY FOR allowing me to take on this project. Writing the fourth edition of Professional JavaScript for Web Developers has been one of the most profoundly challenging yet rewarding projects I've ever worked on, and the patience and support at Wiley was fundamental to getting the book out the door. Thanks to the Wiley staff, specifically Jim Minatel, who put this project in my hands and saw it through.

I'd like to acknowledge Nicholas C. Zakas, the author of the first three editions, for all the work he put in before I became involved. The book would not have amounted to much without the ironclad foundation he laid. I wish him a continued and speedy recovery.

Special thanks to Adaobi Obi Tulton for her guidance. She was an invaluable resource throughout the entire process, and I could not have done it without her patience and expertise.

I'd also like to thank everyone who provided feedback on the book's drafts: Samuel Kallner, Chaim Krause, Marcia Wilbur, Nancy Rapoport, Athiyappan Lalith Kumar, and Evelyn Wellborn. A book like this would fall apart without your contributions.

Finally, I'd like to thank Zach Tratar for writing the foreword. I was fortunate enough to meet Zach the same day I moved to San Francisco. In the years since, he has proven himself to be a feverishly erudite and eminently likeable fellow—not to mention an uncommonly good software engineer. I am honored that he agreed to contribute to this book.

FOREWORD

The industrial revolution was built with steel, and the Internet revolution has been built with JavaScript. Forged and strengthened through constant iteration over the past 25 years, JavaScript's dominance in application development is now hard to question, but that wasn't always the case.

It took only ten days for Brendan Eich to make the first version of JavaScript. It felt fragile, but as history would have it, first impressions aren't everything. Today, every aspect of JavaScript—every detail you'll learn in this book—is the product of hours of debate. Not every decision is ideal and no programming language is perfect, but if you judge one by its ubiquity alone, JavaScript perhaps comes close. It is the only language you can deploy everywhere: servers, desktop browsers, mobile web browsers, and even native mobile applications.

JavaScript is now used by software engineers of all experience levels and backgrounds. It's used by those who care about well-designed, elegant software as well as those who simply want to hack things together to achieve business goals.

How you'll use it is entirely up to you. That power is yours.

Over my last 15 years of developing software, JavaScript tools and best practices have changed dramatically. My experience with the language began in 2004—back when Geocities, Yahoo Groups, and Macromedia Flash player dominated the scene. JavaScript felt like a toy, and I played with some of the popular sandboxes at the time: RSS and MySpace Profile Pages. Helping others modify and customize their personal sites felt like the Wild West and got me hooked.

When I started my first company, configuring a host for your database took days and JavaScript was embedded into your HTML. There were no frontend “applications”—it was all mostly just piecemeal functions. As Ajax became more popular, spearheaded by jQuery, a new world unfolded and applications grew far more robust. That movement accelerated to a breakneck speed and then, suddenly, powerful frameworks were released. Front-end models! Data binding! Route management! Reactive views! It was during this front-end revolution that I moved to Silicon Valley to help start a company founded by Lady Gaga, and quickly, millions of users began using my code. Having now been in Silicon Valley for quite some time, I've led open-source contributions, mentored more software engineers than I can count, and hit a bit of luck, too. My last company was acquired by Stripe in 2018, where I now work to build economic infrastructure for the Internet.

I had the pleasure of meeting Matt the day he first flew out to Palo Alto to lead engineering at a small startup. It was called Claco, and I had recently joined on as an advisor. His energy and passion for great software was apparent, and the fledgling company quickly produced a beautiful product. As has been the Silicon Valley standard since the days of HP, this startup was founded out of a house. But this was no normal home. It was a “hacker house,” where ten or so brilliant software engineers lived at any given moment. Although this was not high-class living—discarded bunk beds and chairs found on the street were commonplace—the quantity and quality of code written there, on a daily basis, was staggering. After work hours, most would simply shift their focus and instead build their side projects for another couple of hours. Those who didn't know how to code were frequently inspired, would get the itch to learn, and become capable within just weeks.

Matt was a driving force at the center of this productivity. He was the most experienced software engineer in the house, and also happened to be the cleanest and most professional, too. Having a formal degree in computer engineering wasn't the norm, so when you saw algorithms, performance calculations, and code written on the windows or whiteboard, you knew Matt was building his next big project. As I got to know him, we became close friends. His intellect, fondness for mentorship, and ability to turn most anything into an A- joke were all qualities I admired.

Even though Matt is an incredibly talented software engineer and engineering leader, it is truly his unique set of experiences and knowledge that make him one of the most qualified people in the world to write this book.

He hasn't just spent his time teaching others—he's done the work.

At Claco, he built out multiple entire products, end-to-end, to help teachers provide a better learning experience in their classrooms. At DoorDash, where he was the first engineer, he built out a robust logistics and delivery network that achieved hyper-growth and is now worth upwards of twelve billion dollars. Finally, at Google, Matt's software has been used by billions of people across the planet.

Massive ownership, massive growth, and massive scale. Most software engineers can go their entire career and experience only one of these, if they're lucky. Matt has not only done all three but has also become a best-selling author in his “spare time,” having written two other books on JavaScript and Angular. Honestly, I just hope his next book unveils the time machine schematics he's clearly hiding from us.

This book is a robust tool filled to the brim with JavaScript knowledge and real-world perspectives. I'm excited for you to continue learning and build whatever you can dream up. Pick it apart, take notes, and don't forget to open up that code editor—after all, the internet revolution is still in the early days!

—Zach Tratar

Software engineer at Stripe

Former co-founder and CEO of Jobstart

INTRODUCTION

A tech lead at Google once shared with me a compelling perspective on JavaScript: It's not really a cohesive programming language—at least not in the formal sense. The ECMA-262 specification defines JavaScript, but there is no single true implementation of it. What's more, the language is far from hermetic. It swims in a veritable ocean of adjacent specifications that govern APIs for everything that JavaScript touches: the DOM, network requests, system hardware, storage, events, files, cryptography, and hundreds of others. Web browsers and their various JavaScript engines all implement these specifications as they see fit. Chrome has Blink/V8, Firefox has Gecko/SpiderMoney, and Safari has WebKit/JavaScriptCore. Browsers will run nearly all JavaScript in a way that conforms to the specifications, but the web is littered with examples of each browser's idiosyncrasies. Therefore, JavaScript is more accurately characterized as a constellation of browser implementations.

Although web purists might insist that JavaScript should not be an integral component of web pages, they must concede that the modern web is severely diminished without it. It is not hyperbolic to say that JavaScript is virtually inescapable: Phones, computers, tablets, televisions, game consoles, smart watches, refrigerators, and even cars now feature web browsers that run JavaScript. Nearly three billion people now use a smartphone that includes a web browser. The language's vibrant community churns out a deluge of high-quality open source projects. Browsers now feature first-class support for APIs that emulate native mobile apps. In Stack Overflow's 2019 Developer Survey, JavaScript was voted the most popular programming language for the seventh consecutive year.

The JavaScript renaissance is upon us.

In this book, JavaScript is covered from its very beginning in the earliest Netscape browsers to the present-day incarnations flush with support for a dizzying spectrum of browser technologies. The book covers a large number of advanced topics in meticulous detail, yet it ensures the reader understands how to use these topics and where they are appropriate. In short, you learn how to apply JavaScript solutions to business problems faced by web developers everywhere.

WHO THIS BOOK IS FOR

This book is aimed at three groups of readers:

  • Experienced developers familiar with object-oriented programming who are looking to learn JavaScript as it relates to traditional OO languages such as Java and C++
  • Web application developers attempting to enhance the usability of their web sites and web applications
  • Novice JavaScript developers aiming to better understand the language

In addition, familiarity with the following related technologies is a strong indicator that this book is for you:

  • Java
  • PHP
  • Python
  • Ruby
  • Golang
  • HTML
  • CSS

This book is not aimed at beginners lacking a basic computer science background or those looking to add some simple user interactions to websites. These readers should instead refer to Wrox's Beginning JavaScript, 5th Edition (Wiley, 2015).

WHAT THIS BOOK COVERS

Professional JavaScript for Web Developers, 4th Edition, provides a developer-level introduction, along with the more advanced and useful features of JavaScript.

The book begins with an exploration of how JavaScript originated and evolved into what it is today. A detailed discussion of the components that make up a JavaScript implementation follows, with specific focus on standards such as ECMAScript and the Document Object Model (DOM).

Building on that base, the book moves on to cover basic concepts of JavaScript, including classes, promises, iterators, and proxies. This is followed by an in-depth examination of client detection, events, animations, forms, errors, and JSON.

The last part of the book is focused on the newest and most important specifications that have emerged in the past few years. This includes fetch, modules, web workers, service workers, and a collection of emerging APIs.

HOW THIS BOOK IS STRUCTURED

This book comprises the following chapters:

  1. What Is JavaScript?—Explains the origins of JavaScript: where it came from, how it evolved, and what it is today. Concepts introduced include the relationship between JavaScript and ECMAScript, the Document Object Model (DOM), and the Browser Object Model (BOM). A discussion of the relevant standards from the European Computer Manufacturer's Association (ECMA) and the World Wide Web Consortium (W3C) is also included.
  2. JavaScript in HTML—Examines how JavaScript is used in conjunction with HTML to create dynamic web pages. Introduces the various ways of embedding JavaScript into a page and includes a discussion surrounding the JavaScript content-type and its relationship to the <script> element.
  3. Language Basics—Introduces basic language concepts, including syntax and flow control statements. Explains the syntactic similarities of JavaScript and other C-based languages and points out the differences. Type coercion is introduced as it relates to built-in operators. Covers all language primitives, including the Symbol type.
  4. Variables, Scope, and Memory—Explores how variables are handled in JavaScript given their loosely typed nature. A discussion of the differences between primitive and reference values is included, as is information about execution context as it relates to variables. Also, a discussion about garbage collection in JavaScript covers how memory is reclaimed when variables go out of scope.
  5. Basic Reference Types—Covers all of the details regarding JavaScript's built-in reference types, such as Date, Regexp, primitives, and primitive wrappers. Each reference type is discussed both in theory and in how they relate to browser implementations.
  6. Collection Reference Types—Continues the book's coverage of built-in reference types with Object, Array, Map, WeakMap, Set, and WeakSet.
  7. Iterators and Generators—Introduces two new fundamental concepts in recent versions of ECMAScript: iterators and generators. Each is discussed both in terms of its most fundamental behavior as well as how it is used in relation to existing language constructs.
  8. Objects, Classes, and Object-Oriented Programming—Explains how to use classes and object-oriented programming in JavaScript. Begins with an in-depth discussion of the JavaScript Object type and continues into coverage of prototypal inheritance. Following this is a complete discussion of ES6 classes and how they are a close sibling of prototypal inheritance.
  9. Proxies and Reflect—Introduces two closely related concepts: Proxy and the Reflect API. These can be used to intercept and shim additional behavior into fundamental operations within the language.
  10. Functions—Explores one of the most powerful aspects of JavaScript: function expressions. Topics include closures, the this object, the module pattern, the creation of private object members, arrow functions, default parameters, and spread operators.
  11. Promises and Async Programming—Introduces two new closely related asynchronous programming constructs: the Promise type and async/await. The chapter begins with a discussion of the asynchronous JavaScript paradigm and continues into coverage of how promises are used and their relationship to async functions.
  12. The Browser Object Model—Introduces the Browser Object Model (BOM), which is responsible for objects allowing interaction with the browser itself. Each of the BOM objects is covered, including window, document, location, navigator, and screen.
  13. Client Detection—Explains various approaches to detecting the client machine and its capabilities. Different techniques include capability detection and user-agent string detection. The chapter covers the pros and cons of each approach, as well as situational appropriateness.
  14. The Document Object Model—Introduces the Document Object Model (DOM) objects available in JavaScript as defined in DOM Level 1. A brief introduction to XML and its relationship to the DOM gives way to an in-depth exploration of the entire DOM and how it allows developers to manipulate a page.
  15. DOM Extensions—Explains how other APIs, as well as the browsers themselves, extend the DOM with more functionality. Topics include the Selectors API, the Element Traversal API, and HTML5 extensions.
  16. DOM Levels 2 and 3—Builds on the previous two chapters, explaining how DOM Levels 2 and 3 augmented the DOM with additional properties, methods, and objects. Includes coverage of DOM4 additions, such as mutation observers.
  17. Events—Explains the nature of events in JavaScript, where they originated, and how the DOM redefined how events should work.
  18. Animation and Graphics with Canvas—Discusses the <canvas> tag and how to use it to create on-the-fly graphics. Both the 2D context and the WebGL (3D) context are covered, providing you with a good starting point for creating animations and games. Includes coverage of both WebGL1 and WebGL2.
  19. Scripting Forms—Explores using JavaScript to enhance form interactions and work around browser limitations. Discussion focuses on individual form elements such as text boxes and select boxes and on data validation and manipulation.
  20. JavaScript APIs—Covers an assortment of JavaScript APIs, including Atomics, Encoding, File, Blob, Notifications, Streams, Timing, Web Components, and Web Cryptography.
  21. Error Handling and Debugging—Discusses how browsers handle errors in JavaScript code and presents several ways to handle errors. Debugging tools and techniques are also discussed for each browser, including recommendations for simplifying the debugging process.
  22. XML in JavaScript—Presents the features of JavaScript used to read and manipulate eXtensible Markup Language (XML) data. Explains the differences in support and objects in various web browsers and offers suggestions for easier cross-browser coding. This chapter also covers the use of eXtensible Stylesheet Language Transformations (XSLT) to transform XML data on the client.
  23. JSON—Introduces the JSON data format as an alternative to XML. Discusses browser-native JSON parsing and serialization as well as security considerations when using JSON.
  24. Network Requests and Remote Resources—Explores all of the most common ways that data and assets are requested by the browser. Includes coverage of the legacy XMLHttpRequest as well as the modern Fetch API.
  25. Client-Side Storage—Discusses how to detect when an application is offline and provides various techniques for storing data on the client machine. Begins with a discussion of the most commonly supported feature, cookies, and then discusses newer functionality such as Web Storage and IndexedDB.
  26. Modules—Discusses the module pattern and its implications on codebases. Following this, the chapter covers pre-ES6 module loaders such as CommonJS, AMD, and UMD. Ends with detailed coverage on the new ES6 module pattern and how to use it properly.
  27. Workers—Covers dedicated workers, shared workers, and service workers in-depth. Includes a discussion of how workers behave both at the operating system and browser level, as well as strategies for how best to use the various types of workers.
  28. Best Practices—Explores approaches to working with JavaScript in an enterprise environment. Techniques for better maintainability are discussed, including coding techniques, formatting, and general programming practices. The chapter also covers execution performance and introduces several techniques for speed optimization. Last, the chapter covers deployment issues, including how to create a build process.

WHAT YOU NEED TO USE THIS BOOK

To run the samples in the book, you need the following:

  • Any modern operating system, such as Windows, Linux, Mac OS, Android, or iOS
  • Any modern browser, such as IE11+, Edge 12+, Firefox 26+, Chrome 39+, Safari 10+, Opera 26+, or iOS Safari 10+

The complete source code is available for download from https://www.wiley.com/en-us/Professional+JavaScript+for+Web+Developers%2C+4th+Edition-p-9781119366447.