Statistics
5
Views
0
Downloads
0
Donations
Support
Share
Uploader

高宏飞

Shared on 2026-04-26

AuthorLaurence Lars Svekis, Maaike van Putten, Rob Percival

Start your journey towards becoming a JavaScript developer with the help of more than 100 fun exercises and projects Key Features: • Write eloquent JavaScript and employ fundamental and advanced features to create your own web apps • Interact with the browser with HTML and JavaScript, and add dynamic images, shapes, and text with HTML5 Canvas • Build a password checker, paint web app, hangman game, and many more fun projects This book demonstrates the capabilities of JavaScript for web application development by combining theoretical learning with code exercises and fun projects that you can challenge yourself with. The guiding principle of the book is to show how straightforward JavaScript techniques can be used to make web apps ranging from dynamic websites to simple browser-based games. The book focuses on key programming concepts and DOM (Document Object Model) manipulations that are used to solve common problems in professional web applications. These include data validation, manipulating the appearance of web pages, working with asynchronous and concurrent code, and much more. The book follows project-based learning to provide context for the theoretical components in a series of code examples that can be used as modules of an application, such as input validators, games, and simple animations. This will be supplemented with a brief crash course on HTML and CSS to illustrate how JavaScript components fit into a complete web application. As you learn the concepts, you can try them in your own editor or browser console to get a solid understanding of how they work and what they do. By the end of this JavaScript book, you will feel confident writing core JavaScript code and be equipped to progress to more advanced libraries, frameworks, and environments such as React, Angular, and Node.js. For: This book is for people who are new to JavaScript (JS) or those looking to build up their skills in web development…

Tags
No tags
Publisher: Packt Publishing
Publish Year: 2021
Language: 英文
Pages: 544
File Format: PDF
File Size: 5.9 MB
Support Statistics
¥.00 · 0times
Text Preview (First 20 pages)
Registered users can read the full content for free

Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.

(This page has no text content)
JavaScript from Beginner to Professional Copyright © 2021 Packt Publishing All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews. Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the authors, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book. Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information. Producer: Tushar Gupta Acquisition Editor – Peer Reviews: Divya Mudaliar Project Editor: Namrata Katare Content Development Editor: Edward Doxey Copy Editor: Safis Editing Technical Editor: Karan Sonawane Proofreader: Safis Editing Indexer: Sejal Dsilva Presentation Designer: Pranit Padwal First published: December 2021 Production reference: 1081221 Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK. ISBN 978-1-80056-252-3 www.packt.com
Contributors About the authors Laurence Lars Svekis is an innovative technology expert with a wide range of expertise and real-world experience in web development, having worked on various web development projects, both large and small, since 1999. He has been a top course instructor since 2015, and has a passion for bringing ideas to life online. Teaching and helping others has been an amazing opportunity for him, as he enjoys sharing knowledge with others. He has an enthusiasm for education and a desire to help others experience the joy of application development and web design. Thanks to Alexis and Sebastian for all their support. Maaike van Putten is a software developer and trainer with a passion for software development and helping others get to the next level in their career. Some of her favorite languages are JavaScript, Java, and Python. She participates as a developer in software development projects and as a trainer in various topics, ranging from IT for dummies to advanced topics for senior software developers. Next to that, she loves to create online content for diverse platforms to help larger audiences. Rob Percival is a highly regarded web developer and Udemy instructor with over 1.7 million students. Over 500,000 of them have taken Rob's Complete Web Developer Course 2.0, as well as his Android Developer and iOS Developer courses.
About the reviewer Chris Minnick is a prolific author, blogger, trainer, speaker, and web developer. His company, WatzThis?, is dedicated to finding better ways to teach computer and programming skills to beginners. Chris has been a full-stack developer for over 25 years and a trainer for over 10 years. He has taught web development, ReactJS, and advanced JavaScript at many of the world's largest companies, as well as at public libraries, co-working spaces, and meetups. Minnick has authored and co-authored over a dozen technical books for adults and kids, including React JS Foundations, HTML and CSS for Dummies, Coding with JavaScript for Dummies, JavaScript for Kids, Adventures in Coding, and Writing Computer Code.
[ v ] Table of Contents Preface xix Chapter 1: Getting Started with JavaScript 1 Why should you learn JavaScript? 2 Setting up your environment 3 Integrated Development Environment 3 Web browser 4 Extra tools 4 Online editor 4 How does the browser understand JavaScript? 4 Using the browser console 5 Practice exercise 1.1 7 Adding JavaScript to a web page 8 Directly in HTML 8 Practice exercise 1.2 9 Linking an external file to our web page 9 Practice exercise 1.3 10 Writing JavaScript code 11 Formatting code 11 Indentations and whitespace 11 Semicolons 12 Code comments 13 Practice exercise 1.4 13 Prompt 14 Random numbers 14 Chapter project 15 Creating an HTML file and a linked JavaScript file 15 Self-check quiz 16 Summary 16
Table of Contents [ vi ] Chapter 2: JavaScript Essentials 17 Variables 18 Declaring variables 18 let, var, and const 19 Naming variables 20 Primitive data types 20 String 21 Escape characters 22 Number 23 BigInt 24 Boolean 25 Symbol 25 Undefined 26 null 26 Analyzing and modifying data types 27 Working out the type of a variable 28 Converting data types 29 Practice exercise 2.1 32 Operators 32 Arithmetic operators 32 Addition 32 Subtraction 33 Multiplication 33 Division 34 Exponentiation 34 Modulus 35 Unary operators: increment and decrement 36 Combining the operators 37 Practice exercise 2.3 38 Assignment operators 38 Practice exercise 2.4 39 Comparison operators 40 Equal 40 Not equal 40 Greater than and smaller than 41 Logical operators 42 And 42 Or 43 Not 43 Chapter project 43 Miles-to-kilometers converter 43 BMI calculator 44 Self-check quiz 44 Summary 45
Table of Contents [ vii ] Chapter 3: JavaScript Multiple Values 47 Arrays and their properties 48 Creating arrays 48 Accessing elements 50 Overwriting elements 50 Built-in length property 51 Practice exercise 3.1 53 Array methods 53 Adding and replacing elements 53 Deleting elements 55 Finding elements 56 Sorting 58 Reversing 58 Practice exercise 3.2 59 Multidimensional arrays 59 Practice exercise 3.3 60 Objects in JavaScript 61 Updating objects 62 Practice exercise 3.4 63 Working with objects and arrays 64 Objects in objects 64 Arrays in objects 65 Objects in arrays 66 Objects in arrays in objects 66 Practice exercise 3.5 67 Chapter projects 68 Manipulating an array 68 Company product catalog 68 Self-check quiz 69 Summary 69 Chapter 4: Logic Statements 71 if and if else statements 72 Practice exercise 4.1 73 else if statements 74 Practice exercise 4.2 75 Conditional ternary operators 76 Practice exercise 4.3 76 switch statements 77 The default case 79 Practice exercise 4.4 80
Table of Contents [ viii ] Combining cases 81 Practice exercise 4.5 82 Chapter projects 82 Evaluating a number game 82 Friend checker game 83 Rock Paper Scissors game 83 Self-check quiz 83 Summary 86 Chapter 5: Loops 87 while loops 88 Practice exercise 5.1 90 do while loops 91 Practice exercise 5.2 92 for loops 92 Practice exercise 5.3 95 Nested loops 95 Practice exercise 5.4 97 Loops and arrays 98 Practice exercise 5.5 100 for of loop 101 Practice exercise 5.6 102 Loops and objects 102 for in loop 103 Practice exercise 5.7 104 Looping over objects by converting to an array 104 break and continue 107 break 108 continue 109 Practice exercise 5.8 111 break, continue, and nested loops 111 break and continue and labeled blocks 113 Chapter project 114 Math multiplication table 114 Self-check quiz 115 Summary 115 Chapter 6: Functions 117 Basic functions 118 Invoking functions 118 Writing functions 118
Table of Contents [ ix ] Naming functions 119 Practice exercise 6.1 120 Practice exercise 6.2 120 Parameters and arguments 120 Practice exercise 6.3 122 Default or unsuitable parameters 122 Special functions and operators 123 Arrow functions 124 Spread operator 125 Rest parameter 127 Returning function values 127 Practice exercise 6.4 129 Returning with arrow functions 129 Variable scope in functions 130 Local variables in functions 130 let versus var variables 132 const scope 133 Global variables 134 Immediately invoked function expression 136 Practice exercise 6.5 137 Recursive functions 138 Practice exercise 6.6 140 Nested functions 140 Practice exercise 6.7 142 Anonymous functions 142 Practice exercise 6.8 143 Function callbacks 143 Chapter projects 145 Create a recursive function 145 Set timeout order 145 Self-check quiz 146 Summary 147 Chapter 7: Classes 149 Object-oriented programming 150 Classes and objects 150 Classes 152 Constructors 152 Practice exercise 7.1 154 Methods 154 Practice exercise 7.2 156
Table of Contents [ x ] Properties 156 Getters and setters 157 Inheritance 159 Prototypes 161 Practice exercise 7.3 163 Chapter projects 163 Employee tracking app 163 Menu items price calculator 163 Self-check quiz 164 Summary 165 Chapter 8: Built-In JavaScript Methods 167 Introduction to built-in JavaScript methods 168 Global methods 169 Decoding and encoding URIs 169 decodeUri() and encodeUri() 170 decodeUriComponent() and encodeUriComponent() 171 Encoding with escape() and unescape() 172 Practice exercise 8.1 172 Parsing numbers 172 Making integers with parseInt() 172 Making floats with parseFloat() 174 Executing JavaScript with eval() 175 Array methods 176 Performing a certain action for every item 176 Filtering an array 177 Checking a condition for all elements 178 Replacing part of an array with another part of the array 178 Mapping the values of an array 179 Finding the last occurrence in an array 179 Practice exercise 8.2 180 Practice exercise 8.3 181 String methods 181 Combining strings 181 Converting a string to an array 182 Converting an array to a string 182 Working with index and positions 183 Creating substrings 185 Replacing parts of the string 185 Uppercase and lowercase 186 The start and end of a string 187
Table of Contents [ xi ] Practice exercise 8.4 188 Practice exercise 8.5 189 Number methods 190 Checking if something is (not) a number 190 Checking if something is finite 190 Checking if something is an integer 191 Specifying a number of decimals 192 Specifying precision 192 Math methods 192 Finding the highest and lowest number 193 Square root and raising to the power of 193 Turning decimals into integers 194 Exponent and logarithm 196 Practice exercise 8.6 196 Date methods 196 Creating dates 197 Methods to get and set the elements of a date 198 Parsing dates 200 Converting a date to a string 200 Practice exercise 8.7 201 Chapter projects 201 Word scrambler 201 Countdown timer 202 Self-check quiz 203 Summary 204 Chapter 9: The Document Object Model 205 HTML crash course 206 HTML elements 206 HTML attributes 210 The BOM 211 Practice exercise 9.1 214 Window history object 214 Window navigator object 215 Window location object 216 Practice exercise 9.2 217 The DOM 217 Additional DOM properties 219 Selecting page elements 220 Practice exercise 9.3 221
Table of Contents [ xii ] Chapter project 222 Manipulating HTML elements with JavaScript 222 Self-check quiz 222 Summary 223 Chapter 10: Dynamic Element Manipulation Using the DOM 225 Basic DOM traversing 226 Practice exercise 10.1 228 Selecting elements as objects 229 Changing innerText 230 Changing innerHTML 230 Accessing elements in the DOM 230 Accessing elements by ID 231 Practice exercise 10.2 232 Accessing elements by tag name 232 Practice exercise 10.3 233 Accessing elements by class name 234 Practice exercise 10.4 234 Accessing elements with a CSS selector 234 Using querySelector() 235 Using querySelectorAll() 236 Element click handler 237 This and the DOM 238 Practice exercise 10.7 239 Manipulating element style 240 Changing the classes of an element 243 Adding classes to elements 243 Removing classes from elements 244 Toggling classes 246 Manipulating attributes 247 Practice exercise 10.8 249 Event listeners on elements 251 Practice exercise 10.9 253 Creating new elements 253 Practice exercise 10.10 255 Chapter projects 256 Collapsible accordion component 256 Interactive voting system 258 Hangman game 259 Self-check quiz 262 Summary 263
Table of Contents [ xiii ] Chapter 11: Interactive Content and Event Listeners 265 Introducing interactive content 266 Specifying events 266 Specifying events with HTML 266 Specifying events with JavaScript 266 Practice exercise 11.1 267 Specifying events with event listeners 267 Practice exercise 11.2 268 The onload event handler 268 Practice exercise 11.3 269 Mouse event handlers 270 Practice exercise 11.4 272 The event target property 272 Practice exercise 11.5 274 DOM event flow 275 Practice exercise 11.6 278 onchange and onblur 280 Practice exercise 11.7 281 Key event handler 282 Practice exercise 11.8 284 Drag and drop elements 285 Practice exercise 11.9 287 Form submission 289 Practice exercise 11.10 291 Animating elements 292 Practice exercise 11.11 293 Chapter projects 294 Build your own analytics 294 Star rating system 295 Mouse position tracker 296 Box clicker speed test game 297 Self-check quiz 299 Summary 299 Chapter 12: Intermediate JavaScript 301 Regular expressions 302 Specifying multiple options for words 303 Character options 304 Groups 307
Table of Contents [ xiv ] Practical regex 309 Searching and replacing strings 310 Email validation 312 Functions and the arguments object 314 Practice exercise 12.3 315 JavaScript hoisting 315 Using strict mode 316 Debugging 317 Breakpoints 318 Practice exercise 12.4 320 Error handling 325 Practice exercise 12.5 326 Using cookies 327 Practice exercise 12.6 329 Local storage 330 Practice exercise 12.7 332 JSON 333 Practice exercise 12.8 336 Parsing JSON 336 Practice exercise 12.9 337 Practice exercise 12.9 answers 337 Chapter projects 338 Email extractor 338 Form validator 339 Simple math quiz 341 Self-check quiz 342 Summary 343 Chapter 13: Concurrency 345 Introducing concurrency 346 Callbacks 346 Practice exercise 13.1 349 Promises 349 Practice exercise 13.2 352 async and await 353 Practice exercise 13.3 354 Event loop 355 Call stack and callback queue 355 Chapter project 359 Password checker 359 Self-check quiz 360 Summary 361
Table of Contents [ xv ] Chapter 14: HTML5, Canvas, and JavaScript 363 Introducing HTML5 with JavaScript 364 Local file reader 365 Uploading files 365 Reading files 367 Practice exercise 14.1 368 Getting position data with GeoLocation 369 HTML5 canvas 370 Practice exercise 14.2 373 Dynamic canvas 373 Adding lines and circles to the canvas 374 Practice exercise 14.3 376 Adding text to the canvas 377 Practice exercise 14.4 378 Adding and uploading images to the canvas 380 Practice exercise 14.5 383 Adding animations to the canvas 383 Practice exercise 14.6 385 Drawing on canvas with a mouse 386 Practice exercise 14.7 389 Saving dynamic images 390 Media on the page 392 Digital accessibility in HTML 394 Chapter projects 395 Create a Matrix effect 395 Countdown clock 397 Online paint app 399 Self-check quiz 401 Summary 402 Chapter 15: Next Steps 403 Libraries and frameworks 404 Libraries 405 jQuery 405 D3 408 Underscore 409 React 410 Frameworks 412 Vue.js 412 Angular 414 Learning the backend 415 APIs 416
Table of Contents [ xvi ] AJAX 417 Practice exercise 15.1 418 Node.js 418 Using the Express Node.js framework 419 Next steps 420 Chapter projects 421 Working with JSON 421 List-making project 421 Self-check quiz 422 Summary 423 Appendix – Practice Exercise, Project, and Self-Check Quiz Answers 425 Chapter 1, Getting Started with JavaScript 425 Practice exercises 425 Projects 426 Creating an HTML file and a linked JavaScript file 426 Self-check quiz 427 Chapter 2, JavaScript Essentials 427 Practice exercises 427 Projects 428 Miles-to-kilometers converter 428 BMI calculator 428 Self-check quiz 429 Chapter 3, JavaScript Multiple Values 429 Practice exercises 429 Projects 431 Manipulating an array 431 Company product catalog 431 Self-check quiz 432 Chapter 4, Logic Statements 432 Practice exercises 432 Projects 434 Evaluating a number game answers 434 Friend checker game answers 435 Rock paper scissors game answers 435 Self-check quiz 436 Chapter 5, Loops 436 Practice exercises 436 Project 441 Math multiplication table 441
Table of Contents [ xvii ] Self-check quiz 442 Chapter 6, Functions 442 Practice exercises 442 Projects 445 Create a recursive function 445 Set timeout order 445 Self-check quiz 446 Chapter 7, Classes 446 Practice exercises 446 Projects 448 Employee tracking app 448 Menu items price calculator 448 Self-check quiz 449 Chapter 8, Built-In JavaScript Methods 449 Practice exercises 449 Projects 452 Word scrambler 452 Countdown timer 452 Self-check quiz 453 Chapter 9, The Document Object Model 453 Practice exercises 453 Projects 454 Manipulating HTML elements with JavaScript 454 Self-check quiz 455 Chapter 10, Dynamic Element Manipulation Using the DOM 456 Practice exercises 456 Projects 461 Collapsible accordion component 461 Interactive voting system 461 Hangman game 462 Self-check quiz 464 Chapter 11, Interactive Content and Event Listeners 465 Practice exercises 465 Projects 473 Build your own analytics 473 Star rater system 474 Mouse position tracker 475 Box clicker speed test game 476 Self-check quiz 477 Chapter 12, Intermediate JavaScript 477 Practice exercises 477
Table of Contents [ xviii ] Projects 482 Email extractor 482 Form validator 483 Simple math quiz 484 Self-check quiz 485 Chapter 13, Concurrency 486 Practice exercises 486 Projects 487 Password checker 487 Self-check quiz 488 Chapter 14, HTML5, Canvas, and JavaScript 489 Practice exercises 489 Projects 496 Create a Matrix effect 496 Countdown clock 497 Online paint app 499 Self-check quiz 500 Chapter 15, Next Steps 501 Practice exercises 501 Projects 501 Working with JSON 501 List-making project 502 Self-check quiz 504 Other Books You May Enjoy 507 Index 513
[ xix ] Preface JavaScript is an amazing multi-functional language that is used a lot for web development (among other things). Any interaction that happens on web pages is JavaScript in action. In fact, all modern browsers understand JavaScript—and soon you will understand it too. This book deals with everything you need to know to create JavaScript applications and use JavaScript on web pages. By the time you finish this book, you'll be capable of creating interactive web pages, dynamic applications, and a lot more as you progress on your professional JavaScript journey! Who this book is for To get started with this book, you don't need any JavaScript experience. However, if you do have some coding experience, you're likely to go through the book and exercises with a bit more ease. Basic familiarity with HTML and CSS would be of benefit. If you're a first-time programmer, we are honored to welcome you to the world of programming in this book. It may seem difficult in the beginning, but we'll guide you right through it. What this book covers Chapter 1, Getting Started with JavaScript, covers some fundamentals of the JavaScript language that you'll have to know to understand the rest of the book. Chapter 2, JavaScript Essentials, deals with essentials such as variables, data types, and operators. Chapter 3, JavaScript Multiple Values, covers how to store multiple values in one variable using arrays and objects.
Preface [ xx ] Chapter 4, Logic Statements, is where the real fun starts: we are going to use logic statements to make decisions for us! Chapter 5, Loops, accounts for situations when it is necessary to repeat a block of code, which is what we use loops for. We are using different types of loops, such as the for and the while loop. Chapter 6, Functions, introduces a very useful block for repeating code snippets: functions! This enables us to invoke a specified code block at any time in our script to do something for us. This will help you to not repeat yourself, which is one of the fundamental principles of writing clean code. Chapter 7, Classes, continues with building blocks of JavaScript that help us to structure our application better. We have already seen how to create objects, and with classes we learn how to create a template for objects that we can reuse anytime we need that particular type of object. Chapter 8, Built-In JavaScript Methods, deals with some great built-in functionality. Functions are something we can write ourselves, but we'll find ourselves using the built-in JavaScript functions often whenever we need to do common tasks, such as checking whether something is a number or not. Chapter 9, The Document Object Model, dives into the browser object model and document object model (DOM). This is going to enrich the way we can use JavaScript by a lot. We'll learn what the DOM is, and how we can affect it with JavaScript and change our websites by doing so. Chapter 10, Dynamic Element Manipulation Using the DOM, demonstrates how to manipulate the elements of the DOM dynamically, which will enable you to create modern user experiences. We can change our website as a response to user behavior such as clicking on a button. Chapter 11, Interactive Content and Event Listeners, takes our responses to the user to the next level. For example, we are going to learn how to respond to events such as the cursor leaving an input box and the mouse of the user moving. Chapter 12, Intermediate JavaScript, deals with topics that you'll need to write intermediate JavaScript code, such as regular expressions, recursion, and debugging, to boost the performance of your code. Chapter 13, Concurrency, introduces the topic of concurrency and asynchronous programming, which will allow our code to do multiple things at the same time and be truly flexible.