📄 Page
1
(This page has no text content)
📄 Page
2
CONTENTS IN DETAIL PRAISE FOR JAVASCRIPT CRASH COURSE TITLE PAGE COPYRIGHT DEDICATION ABOUT THE AUTHOR AND TECHNICAL REVIEWER ACKNOWLEDGMENTS INTRODUCTION Who Is This Book For? Why JavaScript? What Can You Expect to Learn? Online Resources PART I: THE LANGUAGE 1 GETTING STARTED Using the JavaScript Console Using a Text Editor Summary 2 THE BASICS Expressions and Statements Numbers and Operators Order of Operations Floating Point Bindings
📄 Page
3
Variables Constants Naming Conventions Incrementing and Decrementing Addition and Subtraction Assignment Multiplication and Division Assignment Strings Joining Strings Finding the Length of a String Getting a Character from a String Getting Multiple Characters from a String Trimming Whitespace from a String Other Useful String Methods Escape Sequences Template Literals Undefined and Null Booleans Logical Operators Comparison Operators Type Coercion Equality with Coercion Truthiness Uses for Truthiness Summary 3 COMPOUND DATA TYPES Arrays Creation and Indexing Arrays of Arrays Array Methods Objects Creating Objects Accessing Object Values Setting Object Values Working with Objects Nesting Objects and Arrays Nesting with Literals Nesting with Variables Exploring Nested Objects in the Console Printing Nested Objects with JSON.stringify Summary 4 CONDITIONALS AND LOOPS Making Decisions with Conditionals
📄 Page
4
if Statements if…else Statements More Complex Conditions Chained if…else Statements Repeating Code with Loops while Loops for Loops for…of Loops for…in Loops Summary 5 FUNCTIONS Declaring and Calling Functions Return Values Parameter Types Side Effects Passing a Function as an Argument Other Function Syntaxes Function Expressions Arrow Functions Rest Parameters Higher-Order Functions Array Methods That Take Callbacks Custom Functions That Take Callbacks Functions That Return Functions Summary 6 CLASSES Creating Classes and Instances Inheritance Prototype-Based Inheritance Using Constructors and Prototypes Comparing Constructors and Classes Exploring Object.prototype Walking the Prototype Chain Overriding a Method Summary PART II: INTERACTIVE JAVASCRIPT 7 HTML, THE DOM, AND CSS
📄 Page
5
HTML Creating an HTML Document Understanding Nested Relationships The Document Object Model The DOM API Element Identifiers script Elements CSS link Elements Rulesets Selectors Using CSS Selectors in JavaScript Summary 8 EVENT-BASED PROGRAMMING Event Handlers Event Bubbling Event Delegation Mouse Movement Events Keyboard Events Summary 9 THE CANVAS ELEMENT Creating a Canvas Making Static Drawings Drawing Outlined Rectangles Drawing Other Shapes Using Paths Interacting with the Canvas Animating the Canvas Summary PART III: PROJECTS PROJECT 1: CREATING A GAME 10 PONG The Game Setup The Ball Refactoring
📄 Page
6
The Game Loop Bouncing The Paddles Moving the Paddles with Player Input Detecting Paddle Collisions Bouncing Near the Paddle Ends Scoring Points Computer Control Game Over The Complete Code Summary 11 OBJECT-ORIENTED PONG Object-Oriented Design The File Structure The GameView Class The Game Elements The Paddles The Ball The Scores and Computer Classes The Game Class Starting the Game Summary PROJECT 2: MAKING MUSIC 12 GENERATING SOUNDS The Web Audio API Setting Up Generating a Tone with the Web Audio API The Tone.js Library Generating a Tone with Tone.js Understanding the Tone.Synth Options Playing More Notes in Sequence Playing Multiple Notes at Once The Tone.js Transport Tone.Loop Tone.Sequence Tone.Part Making Drum Sounds Hi-Hat Synthesis Snare Synthesis Kick Synthesis
📄 Page
7
Reverb A Drum Loop Working with Samples Summary 13 WRITING A SONG Getting Organized Event Handling Making the Drumbeat Adding the Bass Lines Adding Chords Playing a Tune The Complete Code Summary PROJECT 3: VISUALIZING DATA 14 INTRODUCING THE D3 LIBRARY The SVG Graphics Format Grouping Elements Drawing Circles Defining Paths Styling Elements with CSS Adding Interactivity with JavaScript The D3 Library Setup Selections Data Binding Data Joins Real-Time Updates Transitions and Key Functions Advanced Joins Creating a Bar Graph Setting Up Calculating Character Frequencies Drawing the Bar Graph Styling with CSS and Regular Expressions Cleaning the Data Animating the Changes Summary 15 VISUALIZING DATA FROM THE GITHUB SEARCH API
📄 Page
8
Setting Up Fetching Data The Basic Visualization Creating the Elements Drawing the Axes Drawing the Bars Improving the Visualization Showing Repository Info Color-Coding the Bars Labeling the Left Axis Adding Interactivity Filtering the Data by License Animating the Changes The Complete Code Summary AFTERWORD INDEX
📄 Page
9
PRAISE FOR JAVASCRIPT CRASH COURSE “JavaScript Crash Course is the perfect no-nonsense guide for folks who just want to roll their sleeves up and pick up the basics from scratch. It skips the distractions that often complicate a mastery of web programming, like UI frameworks, build tools, and server tech, using real projects to give aspiring web engineers a solid foundation.” —JED SCHMIDT, FOUNDER OF BROOKLYNJS “JavaScript Crash Course is a fun, practical, hands-on introduction that I wish I had when I was learning JavaScript. Readers can learn from the very basics all the way through making real games and applications that are relevant to ‘real-world’ development practices.” —CASSIDY WILLIAMS (@CASSIDOO), STARTUP ADVISOR AND CTO AT CONTENDA “JavaScript Crash Course offers practical, pragmatic, and project-based education on how to think about and work with JavaScript. Nick Morgan has the experience to introduce you to the language with examples that build on each other, and he quickly dives into creating real projects. As you delve deeper into the book, you’ll realize that your building blocks are the internet itself. You’ll find yourself using audio and sound generation techniques, painting with the Canvas API, and pulling in third-party JavaScript libraries. By the time you complete the crash course, you’ll be ready to start your own projects. Nick is providing a wonderful service with his hands-on teaching, both here and in JavaScript for Kids. I hope you enjoy the book as much as I did.” —SCOTT HANSELMAN (@SHANSELMAN), VP OF DEVELOPER COMMUNITY AT MICROSOFT “Nick has managed to condense the foundational concepts of JavaScript into concise, approachable descriptions that are easily accessible to beginners. Throw in some fun lessons in graphics and sound to create a
📄 Page
10
game, and you’ve got an excellent and engaging JavaScript book that’s well worth your time.” —NICHOLAS C. ZAKAS (@SLICKNET), CREATOR OF ESLINT AND VETERAN JAVASCRIPT BOOK AUTHOR
📄 Page
11
JAVASCRIPT CRASH COURSE A Hands-On, Project-Based Introduction to Programming by Nick Morgan San Francisco
📄 Page
12
JAVASCRIPT CRASH COURSE. Copyright © 2024 by Nick Morgan. All rights reserved. No part of this work may be reproduced or transmitted in any form or by any means, electronic or mechanical, including photocopying, recording, or by any information storage or retrieval system, without the prior written permission of the copyright owner and the publisher. First printing ISBN-13: 978-1-7185-0226-0 (print) ISBN-13: 978-1-7185-0227-7 (ebook) Published by No Starch Press®, Inc. 245 8th Street, San Francisco, CA 94103 phone: +1.415.863.9900 www.nostarch.com; info@nostarch.com Publisher: William Pollock Managing Editor: Jill Franklin Production Manager: Sabrina Plomitallo-González Production Editor: Miles Bond Developmental Editor: Nathan Heidelberger Cover Illustrator: Gina Redman Interior Design: Octopod Studios Technical Reviewer: Angus Croll Copyeditor: Rachel Head Proofreader: Scout Festa Indexer: BIM Creatives, LLC Library of Congress Control Number: 2023030044 For customer service inquiries, please contact info@nostarch.com. For information on distribution, bulk sales, corporate sales, or translations: sales@nostarch.com. For permission to translate this work: rights@nostarch.com. To report counterfeit copies or piracy: counterfeit@nostarch.com. No Starch Press and the No Starch Press logo are registered trademarks of No Starch Press, Inc. Other product and company names mentioned herein may be the trademarks of their respective owners. Rather than use a trademark symbol with every occurrence of a trademarked name, we are using the names only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark. The information in this book is distributed on an “As Is” basis, without warranty. While every precaution has been taken in the preparation of this work, neither the author nor No Starch Press, Inc. shall have any liability to any person or entity with respect to any loss or damage caused or alleged to be caused directly or indirectly by the information contained in it.
📄 Page
13
To Lyra and Hazel
📄 Page
14
About the Author Nick Morgan is the author of JavaScript for Kids (No Starch Press, 2014). He’s a software engineer at Airbnb, working on some of the core services that keep the site running. Prior to that, he worked at Twitter, starting on the web team and writing JavaScript to help build the main website before moving to the backend Tweets service, where he helped design the Edit Tweet feature. Nick grew up in the UK and has a degree in music and sound recording from the University of Surrey. He lives in Colorado with his wife, two daughters, three cats, and one dog. About the Technical Reviewer Originally from the UK, Angus Croll now lives in the San Francisco Bay Area, where he currently works on all things performance at Netflix. A devotee of both literary fiction and JavaScript, he’s the author of If Hemingway Wrote JavaScript (No Starch Press, 2014), as well as the official Babel song. He also wrote and maintains the popular Just utility library.
📄 Page
15
ACKNOWLEDGMENTS First of all, thank you to my wife, Philly, and our kids, Lyra and Hazel, for making this all worth it. I’m sorry so many of my evenings have been taken up with writing, and I promise I won’t write another book for at least a year! Thanks to Bill Pollock for trusting me to write a second JavaScript book, to my editor Nathan Heidelberger for your excellent work in shaping my text (and for putting up with my many delays!), and to everyone else at No Starch for your work in turning this book into reality. Thank you to my friend and tech reviewer Angus Croll for everything. Angus referred me to Twitter and later referred me to Bill Pollock—I wouldn’t be here writing this if it weren’t for him. Finally, thanks to my parents for giving me the curiosity and optimism that ultimately led me to write this book.
📄 Page
16
INTRODUCTION I vividly remember the first time I “wrote” JavaScript. I’d been messing around with web design and copy-pasted some code from another website to add some weird effects whenever the mouse hovered over certain parts of the page. I had no idea what the code was doing, but through trial and error I managed to get something working. JavaScript is a very forgiving language—sometimes to a fault—and that made it a very gentle introduction to programming for me and countless others. So many people have chosen JavaScript as a first programming language because of how easy it is to get started: it’s right there waiting for you in your web browser!
📄 Page
17
Who Is This Book For? The aim of this book is to get you writing real JavaScript code as quickly as possible, teaching all the essentials without getting bogged down in the intricacies of the language. I don’t expect you to have any prior programming experience. If you’re comfortable using a computer for everyday tasks like browsing the internet and editing documents, you have everything you need to get started. JavaScript Crash Course is written for individuals of all ages who want to learn JavaScript independently through hands-on examples and projects. Maybe you want to transition into a career in computer programming, or you want to pursue coding as a hobby. Perhaps you’ve worked in other programming languages, and you need to get up to speed in JavaScript. If you’re a teacher and are looking for an easy way to introduce your students to programming, JavaScript Crash Course is a great option for you, too. Why JavaScript? There are hundreds of programming languages to choose from, but there are a few things that make JavaScript special. Most important is its relationship with web browsers, such as Google Chrome, Safari, Microsoft Edge, and Firefox. Almost every web browser can run JavaScript, which means the code you write in JavaScript can be run on any computer with a web browser. There’s no need to install any additional special software. Almost all smartphone web browsers can run JavaScript, too, so you may have a JavaScript-enabled browser in your pocket or bag right now. Because of its relationship to web browsers, JavaScript is an extremely important part of web development. If a website includes dynamic, interactive features, it was probably created with JavaScript. For example, YouTube uses JavaScript to show you previews of videos when you hover over their thumbnails, Threads uses JavaScript to load more posts as you scroll down the page, and Amazon uses JavaScript to power its Look Inside feature. Beyond its use in web browsers, JavaScript is also heavily used on the backend of websites, or the part of the website code that runs on a server, delivering content to users (as opposed to the frontend code that runs
📄 Page
18
directly on the user’s device). This is possible via a technology called Node.js. Many top websites have a Node.js backend, letting you use the same language for the frontend and backend of your website, and even share code between the two. Finally, JavaScript has become a very popular scripting language for various applications, from Photoshop (where you can automate image processing) to Gmail (where you can add automations that organize your email). With some JavaScript knowledge, you can bend these applications to your will! While the language is useful in all these areas, this book will focus solely on browser-based JavaScript. There are a few reasons for this. First, as I’ve already mentioned, one of the great advantages of running JavaScript in a browser is that you don’t have to install anything special to get started. I didn’t want to begin the book with a tedious chapter on installing Node.js on your computer—a chapter that could become outdated as soon as it was written. Second, while virtually all websites use JavaScript for the frontend, JavaScript is just one among many possible languages for writing backend code. The browser is by far the most universally applicable context for learning JavaScript. I still highly recommend checking out Node.js and other uses for JavaScript after you finish this book and have some experience with the language. You should see the book as a jumping-off point: the beginning, rather than the end, of your JavaScript education. For more on next steps once you’ve worked through the book, see the afterword. What Can You Expect to Learn? This book will teach you browser-based JavaScript. Beyond learning the JavaScript language itself, you’ll also learn skills that will help you in any programming language, such as how to think about problems and how to structure programs. You’ll build a foundation of programming knowledge that will stick with you throughout your professional and personal coding endeavors. Part I of this book lays out the basics of the language. I’ve been very intentional about the ordering of language concepts and features, making sure that every new concept builds on previous ones and never introducing
📄 Page
19
anything that doesn’t have a solid foundation. Here’s what you’ll find in this part of the book: Chapter 1: Getting Started Shows you how to write your first lines of JavaScript in both a web browser and a text editor. Chapter 2: The Basics Introduces basic ingredients of JavaScript programs, like expressions, statements, and variables, and explains how to use simple data types to represent numbers, text, and true/false values. Chapter 3: Compound Data Types Discusses arrays and objects, which let you combine multiple pieces of data into more meaningful collections. Chapter 4: Conditionals and Loops Teaches you to add logic to your programs with control structures that can make decisions and repeat segments of code. Chapter 5: Functions Shows you how to create reusable pieces of code with functions. Chapter 6: Classes Helps you add more structure to your code with classes and object-oriented programming principles. Part II of the book discusses how to use JavaScript to work with web browsers. This section explores important techniques for creating interactive web applications: Chapter 7: HTML, the DOM, and CSS Explains how to write web pages in HyperText Markup Language (HTML) and modify their content with JavaScript using the Document Object Model (DOM). You’ll also learn how to apply basic styling to web pages using Cascading Style Sheets (CSS). Chapter 8: Event-Based Programming Shows how to trigger JavaScript code in response to user behaviors such as mouse clicks and key presses. Chapter 9: The Canvas Element Teaches you to draw graphics and animations in the browser with JavaScript using the Canvas API.
📄 Page
20
Finally, Part III of the book lets you put the skills you gained in Parts I and II to use through a series of projects. There are no dependencies between the projects, so you can tackle them in any order, or only work on the projects you find most interesting. I would recommend completing all of them if possible, as they all introduce some valuable general-purpose programming concepts. Each project spans two chapters: Project 1: Creating a Game Guides you through making your own version of the classic Atari game Pong. This project will put to use your skills with the Canvas API and tie together all the basics you learned about data structures, conditionals, and functions. After you’ve developed the game in Chapter 10, Chapter 11 shows you how to restructure its code using classes and object-oriented design principles. Project 2: Making Music Explores how to make music using JavaScript. Chapter 12 explains how to use the Web Audio API and a library called Tone.js to generate sounds. Then Chapter 13 puts together what you’ve learned to create a song. Once you’ve completed this project, you’ll not only be able to create your own music, but you’ll also have gained some experience working with complex third- party libraries. Project 3: Visualizing Data Introduces you to the world of data visualization using the popular D3 library. Chapter 14 teaches the basics of D3 and Scalable Vector Graphics (SVG), an alternative to the Canvas API for drawing in the browser. Then, in Chapter 15, you’ll build an application to dynamically visualize data loaded from across the internet. This project illustrates how to request data through a third- party API, an important programming skill. Online Resources This book features a number of hands-on exercises so you can practice what you’ve learned. I encourage you to try them all out yourself, but if you get stuck or you just want to check your answers, solutions are available online at https://codepen.io/collection/ZMjYLO. There you’ll also find complete, downloadable code files for the book’s projects.