Professional Javascript® for Web Developers
Published by
John Wiley & Sons, Inc.
10475 Crosspoint Boulevard
Indianapolis, IN 46256www.wiley.com
Copyright © 2020 by John Wiley & Sons, Inc., Indianapolis, Indiana
Published simultaneously in Canada
ISBN: 978-1-119-36644-7
ISBN: 978-1-119-36635-5 (ebk)
ISBN: 978-1-119-36657-7 (ebk)
No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108 of the 1976 United States Copyright Act, without either the prior written permission of the Publisher, or authorization through payment of the appropriate per-copy fee to the Copyright Clearance Center, 222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 646-8600. Requests to the Publisher for permission should be addressed to the Permissions Department, John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030, (201) 748-6011, fax (201) 748-6008, or online at http://www.wiley.com/go/permissions
.
Limit of Liability/Disclaimer of Warranty: The publisher and the author make no representations or warranties with respect to the accuracy or completeness of the contents of this work and specifically disclaim all warranties, including without limitation warranties of fitness for a particular purpose. No warranty may be created or extended by sales or promotional materials. The advice and strategies contained herein may not be suitable for every situation. This work is sold with the understanding that the publisher is not engaged in rendering legal, accounting, or other professional services. If professional assistance is required, the services of a competent professional person should be sought. Neither the publisher nor the author shall be liable for damages arising herefrom. The fact that an organization or Web site is referred to in this work as a citation and/or a potential source of further information does not mean that the author or the publisher endorses the information the organization or Web site may provide or recommendations it may make. Further, readers should be aware that Internet Web sites listed in this work may have changed or disappeared between when this work was written and when it is read.
For general information on our other products and services please contact our Customer Care Department within the United States at (877) 762-2974, outside the United States at (317) 572-3993 or fax (317) 572-4002.
Wiley publishes in a variety of print and electronic formats and by print-on-demand. Some material included with standard print versions of this book may not be included in e-books or in print-on-demand. If this book refers to media such as a CD or DVD that is not included in the version you purchased, you may download this material at http://booksupport.wiley.com
. For more information about Wiley products, visit www.wiley.com
.
Library of Congress Control Number: 2018956541
Trademarks: Wiley, the Wiley logo, Wrox, the Wrox logo, Programmer to Programmer, and related trade dress are trademarks or registered trademarks of John Wiley & Sons, Inc. and/or its affiliates, in the United States and other countries, and may not be used without written permission. JavaScript is a registered trademark of Oracle America, Inc. All other trademarks are the property of their respective owners. John Wiley & Sons, Inc., is not associated with any product or vendor mentioned in this book.
To Jordan, for her unwavering support no matter how many times she heard “it's almost done.”
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
.
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.
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.
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
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.
This book is aimed at three groups of readers:
In addition, familiarity with the following related technologies is a strong indicator that this book is for you:
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).
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.
This book comprises the following chapters:
<script>
element.Symbol
type.Date
, Regexp
, primitives, and primitive wrappers. Each reference type is discussed both in theory and in how they relate to browser implementations.Object
, Array
, Map
, WeakMap
, Set
, and WeakSet
.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.Proxy
and the Reflect
API. These can be used to intercept and shim additional behavior into fundamental operations within the language.this
object, the module pattern, the creation of private object members, arrow functions, default parameters, and spread operators.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.window
, document
, location
, navigator
, and screen
.<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.XMLHttpRequest
as well as the modern Fetch API.To run the samples in the book, you need the following:
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
.