Head First JavaScript Programming A Learners Guide to Modern JavaScript, 2nd Edition (Eric Freeman, Elisabeth Robson) (Z-Library)

Author: Eric Freeman, Elisabeth Robson

JavaScript

No Description

📄 File Format: PDF
💾 File Size: 49.7 MB
31
Views
0
Downloads
0.00
Total Donations

📄 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.

📄 Page 1
(This page has no text content)
📄 Page 2
(This page has no text content)
📄 Page 3
“This book unlocks the power of JavaScript in a way that’s never been done before! It engages the reader with a dynamic experience. Say goodbye to boring code tutorials and hello to a fun, innovative way to master one of the most popular programming languages out there. Get ready to revolutionize the way you learn JavaScript!” — Doreen Lorenzo, Assistant Dean, School of Design and Creative Technologies, University of Texas at Austin “JavaScript is fundamental to the Web; if JavaScript were somehow to disappear, the Web as we know it would be gone. Everyone who is interested in Web software must know JavaScript– and, naturally, there are a million ways to learn it. But if I had to pick the best way, that would be easy: this book. The authors have known JavaScript inside-out since it was born. (In fact Java itself was inspired, according to one of its founders, by fundamental work in distributed programming accomplished by Freeman, Robson and their colleagues at Yale.) The authors also happen to have a rare ability to write about technical topics in a clear, straightforward way. Freeman and Robson are two of the best teachers around, and no one knows JavaScript better than they do. This is one of those rare books about software and computing that I can recommend without reservation.” — David Gelernter, Professor of Computer Science, Yale University “Bullseye! Eric Freeman and Elisabeth Robson did it again. The clear, engaging, conversational tone of Head First JavaScript Programming coupled with accessible examples, exercises, and reader challenges, results in an indispensable tool for motivated, independent learners. Many of the illustrative problems will be familiar to readers of Head First Learn to Code and thus presents a unique opportunity for instructors to integrate both texts for curious and precocious students to compare and contrast languages, syntax, and fundamental concepts of each. I look forward to incorporating this new book in future student enrichment courses.” — Josh Sharfman, Shalhevet High School, Computer Science “As a high school teacher, I highly recommend Freeman and Robson’s standard-setting JavaScript guide. Their unique combination of precise computer science with engaging teaching skills makes complex concepts intuitive and accessible, turning learning into a delight for students. The innovative multi-sensory approach ensures that challenging topics are enjoyable for students of all experience levels. With Freeman and Robson, JavaScript programming becomes an adventure that blends imagination with practical skills—an essential resource for any school’s computer science curriculum.” — Bryce Carlisle, co-founder of Waterloo School, Austin, Texas “A unique combination of deep programming topics and lessons with fun applicable interactions and tasks as proof of proficiency along the way.” — Mk Haley, Themed Entertainment Association and former Disney Imagineer Praise for Head First JavaScript Programming
📄 Page 4
Praise for other books by Eric Freeman and Elisabeth Robson “I feel like a thousand pounds of books have just been lifted off of my head.” — Ward Cunningham, inventor of the Wiki “This book’s admirable clarity, humor and substantial doses of clever make it the sort of book that helps even non-programmers think well about problem-solving.” — Cory Doctorow, co-editor of Boing Boing, science fiction author “The highly graphic and incremental approach precisely mimics the best way to learn this stuff...” — Danny Goodman, author of Dynamic HTML: The Definitive Guide and JavaScript & DHTML Cookbook
📄 Page 5
Other related books from O’Reilly Head First HTML5 Programming JavaScript: The Definitive Guide JavaScript Enlightenment Other O’Reilly books by Eric T. Freeman and Elisabeth Robson Head First Design Patterns Head First HTML and CSS Head First Learn to Code Head First HTML5 Programming Other books in O’Reilly’s Head First series Head First Design Patterns Head First HTML and CSS Head First Java Head First Software Architecture Head First SQL Head First Git Head First C# Head First Python Head First jQuery Head First Android Development Head First Swift
📄 Page 6
(This page has no text content)
📄 Page 7
Head First JavaScript Programming Wouldn’t it be dreamy if there was a JavaScript book that was more fun than going to the dentist and more revealing than an IRS form? It’s probably just a fantasy... Eric Freeman Elisabeth Robson Boston Farnham Sebastopol TokyoBeijing
📄 Page 8
Head First JavaScript Programming by Eric Freeman and Elisabeth Robson Copyright © 2024 O’Reilly Media, Inc. All rights reserved. Printed in the United States of America. Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472. O’Reilly Media books may be purchased for educational, business, or sales promotional use. Online editions are also available for most titles (oreilly.com). For more information, contact our corporate/institutional sales department: (800) 998-9938 or corporate@oreilly.com. Series Creators: Kathy Sierra and Bert Bates Series Advisors: Eric Freeman and Elisabeth Robson Acquisitions Editor: David Michelson Development Editor: Michele Cronin Production Editor: Christopher Faucher Proofreader: Rachel Head Indexer: Potomac Indexing, LLC Cover Design: Susan Thompson, based on a series design by Ellie Volckhausen Cover and Interior Illustrations: José Marzan Jr. Printing History: September 2014: First Edition August 2024: Second Edition The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. The Head First series designations, Head First JavaScript Programming, and related trade dress are trademarks of O’Reilly Media, Inc. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and O’Reilly Media, Inc., was aware of a trademark claim, the designations have been printed in caps or initial caps. While every precaution has been taken in the preparation of this book, the publisher and the authors assume no responsibility for errors or omissions, or for damages resulting from the use of the information contained herein. No variables were harmed in the making of this book. ISBN: 978-1-098-14794-5 [LSI] [2024-08-21]
📄 Page 9
To JavaScript—you weren’t born with a silver spoon in your mouth, but you’ve outclassed every language that’s challenged you in the browser.
📄 Page 10
viii the authors Authors of Head First JavaScript Programming Eric Freeman Elisabeth Robson Elisabeth is a software engineer, writer, and trainer. She has been passionate about technology since her days as a student at Yale University, where she earned a masters of science in computer science and designed a concurrent, visual programming language and software architecture. Elisabeth’s been involved with the internet since the early days; she co-created the award-winning website, The Ada Project, one of the first websites designed to help women in computer science find career and mentorship information online. She cofounded WickedlySmart, an online education experience centered on web technologies, where she currently creates books, articles, videos, and more. Previously, as Director of Special Projects at O’Reilly Media, Elisabeth produced in-person workshops and online courses on a variety of technical topics and developed her passion for creating learning experiences to help people understand technology. Prior to her work with O’Reilly, Elisabeth spent time spreading fairy dust at The Walt Disney Company, where she led research and development efforts in digital media. When not in front of her computer, you’ll find Elisabeth hiking, cycling, or kayaking in the great outdoors with her camera nearby, or cooking vegetarian meals. You can send her email at beth@wickedlysmart.com. Eric is described by Head First series co-creator Kathy Sierra as “one of those rare individuals fluent in the language, practice, and culture of multiple domains from hipster hacker to corporate VP, engineer, think tank.” Eric is deeply involved in education. He is currently on faculty at the University of Texas at Austin, where he teaches creative coding in the School of Design and Creative Technology. He also advises the Head First series at O’Reilly and frequently teaches live courses on their platform. This is in addition to the five books he’s written for O’Reilly, covering the spectrum from beginner coding books to advanced object-oriented design. By training, Eric is a computer scientist, having studied with industry luminary David Gelernter during his Ph.D. work at Yale University. Eric also spent a decade as a media company executive, having held the position of CTO of Disney Online and Disney.com at The Walt Disney Company. Today, besides his academic ties, he works for WickedlySmart, an online education company. Write to Eric at eric@wickedlysmart.com or visit his site at http://ericfreeman.com.
📄 Page 11
table of contents ix Table of Contents (Summary) Table of Contents (the real thing) Your brain on JavaScript. Here you are trying to learn something, while here your brain is doing you a favor by making sure the learning doesn’t stick. Your brain’s thinking, “Better leave room for more important things, like which wild animals to avoid and whether naked snowboarding is a bad idea.” So how do you trick your brain into thinking that your life depends on knowing JavaScript? Intro Who is this book for? xxiv We know what you’re thinking xxv Metacognition xxvii Bend your brain into submission xxix Read me xxx The technical review team xxxiii Acknowledgments xxxiv Intro xxiii 1 A quick dip into JavaScript: Getting your feet wet 1 2 Writing real code: Going further 47 3 Introducing functions: Getting functional 83 4 Putting some order in your data: Arrays 131 5 Understanding objects: A trip to Objectville 181 6 Interacting with your web page: Getting to know the DOM 239 7 Types, equality, conversion, and all that jazz: Serious types 275 8 Bringing it all together: Building an app 331 9 Handling events: Getting asynchronous 397 10 Anonymous and higher-order functions: Liberated functions 445 11 Modern syntax, lexical scope, and closures: Serious functions 491 12 Advanced object construction: Creating objects 543 A Leftovers: The top ten things (we didn’t cover) 593 Index 609
📄 Page 12
table of contents x The way JavaScript works 2 How you’re going to write JavaScript 3 How to get JavaScript into your page 4 JavaScript, you’ve come a long way... 6 How to make a statement 10 Variables and values 11 Constants, another kind of variable 12 Back away from that keyboard! 14 Express yourself 17 Doing things more than once 19 How the while loop works 20 Making decisions with JavaScript 24 And, when you need to make LOTS of decisions 25 Reach out and communicate with your user 27 A closer look at console.log 29 Opening the console 30 Coding a Serious JavaScript Application 31 How do I add code to my page? (let me count the ways!) 34 We’re going to have to separate you two 35 Getting your feet wet1 a quick dip into javascript JavaScript gives you superpowers. The true programming language of the web, JavaScript lets you add behavior to your web pages. No more dry, boring, static pages that just sit there looking at you— with JavaScript, you’ll be able to reach out and touch your users, react to interesting events, grab data from the web to use in your pages, draw graphics right into those pages, and a lot more. And once you know JavaScript, you’ll also be in a position to create totally new behaviors for your users. You’ll be in good company, too. JavaScript’s not only one of the most popular programming languages, it’s also supported in all modern browsers and is used in many environments outside of the browser. More on that later; for now, let’s get started!
📄 Page 13
table of contents xi Going further You already know about variables, types, expressions... we could go on. The point is, you already know a few things about JavaScript. In fact, you know enough to write some real code. Some code that does something interesting, some code that someone would want to use. What you’re lacking is the real experience of writing code, and we’re going to remedy that right here and now. How? By jumping in head first and coding up a casual game, all written in JavaScript. Our goal is ambitious, but we’re going to take it one step at a time. Come on, let’s get this started, and if you want to launch the next startup, we won’t stand in your way; the code is yours. writing real code 2 Let’s build a Battleship game 48 First, a high-level design 49 Working through the Pseudocode 51 Oh, before we go any further, don’t forget the HTML! 53 Writing the Simple Battleship code 54 Now let’s write the game logic 55 Step 1: Setting up the loop, getting some input 56 How prompt works 57 Step 2: Checking the user’s guess 58 Adding the hit detection code 61 Step 3: Hey, you sank my battleship! 61 Step 4: Provide some post-game analysis 62 Doing a little quality assurance 65 Can we talk about your verbosity... 69 Finishing the Simple Battleship game 70 The recipe for generating a random number 71 Congrats on your first true JavaScript program, and a short word about reusing code 75
📄 Page 14
table of contents xii Get ready for your first superpower. You’ve got some programming under your belt; now it’s time to really move things along with functions. Functions give you the power to write code that can be applied to all sorts of different circumstances, code that can be reused over and over, code that is much more manageable, code that can be abstracted away and given a simple name so you can forget all the complexity and get on with the important stuff. You’re going to find not only that functions are your gateway from scripter to programmer, but that they’re the key to the JavaScript programming style. In this chapter, we’re going to start with the basics—the mechanics, the ins and outs of how functions really work—and then you’ll keep honing your function skills throughout the rest of the book. So, let’s get a good foundation started, now. What’s wrong with the code, anyway? 85 By the way, did we happen to mention FUNCTIONS? 87 Okay, but how does it actually work? 88 What can you pass to a function? 93 JavaScript is pass-by-value. 96 Weird Functions 98 Functions can return things too 99 Tracing through a function with a return statement 100 Global and local variables 103 Knowing the scope of your local and global variables 105 There’s more to the story 106 Don’t forget to declare your locals! 108 The short lives of variables 109 Getting functional3 introducing functions
📄 Page 15
table of contents xiii Arrays There’s more to JavaScript than numbers, strings, and booleans. So far you’ve been writing JavaScript code with primitives—strings, numbers, and booleans, like “Fido”, 23, and true. You can do a lot with primitive types, but at some point you’ve got to deal with more data. Say, all the items in a shopping cart, or all the songs in a playlist, or a set of stars and their apparent magnitude, or an entire product catalog. For that you need a little more oomph. The type of choice for this kind of ordered data is a JavaScript array, and in this chapter we’re going to walk through how to put your data into an array, how to pass it around, and how to operate on it. We’ll be looking at a few other ways to structure your data in later chapters, but let’s get started with arrays. putting some order in your data 4 Can you help Bubbles-R-Us? 132 How to represent multiple values in JavaScript 132 How arrays work 134 How big is that array anyway? 136 The Phrase-O-Matic 138 Meanwhile, back at Bubbles-R-Us... 141 How to iterate over an array 144 But wait, there’s a better way to iterate over an array 146 It’s that time again...can we talk about your verbosity? 153 Redoing the for loop with the post-increment operator 154 Creating an array from scratch (and adding to it) 158 And the winners are... 162 A quick survey of the code 164 Writing the printAndGetHighScore function 165 Refactoring the code using printAndGetHighScore 166 Putting it all together 168
📄 Page 16
table of contents xiv Did someone say “objects”?! 182 Thinking about properties... 183 How to create an object 185 What is “object-oriented” anyway? 188 How properties work 189 How does a variable hold an object? Inquiring minds want to know... 194 Comparing primitives and objects 195 Doing even more with objects 196 Does the taxi cut it? 197 Let’s talk a little more about passing objects to functions 200 The Auto-O-Matic 203 Oh, behave! Or, how to add behavior to your objects 206 Improving the drive method 207 Uh-oh, not so fast... 209 Why doesn’t the drive method know about the started property? 210 How “this” works 212 Method shorthand 218 How behavior affects state 219 Now let’s affect the behavior with the state 220 Congrats on your first objects! 222 Guess what? There are objects all around you! 223 A trip to Objectville5 understanding objects So far, you’ve been using primitives and arrays in your code. And you’ve approached coding in quite a procedural manner, using simple statements, conditionals, and for/while loops with functions—that’s not exactly object-oriented. In fact, it’s not object-oriented at all! You did use a few objects here and there without really knowing it, but you haven’t written any of your own objects yet. Well, the time has come to leave this boring procedural town behind and create some objects of your own. In this chapter, you’re going to find out why using objects is going to make your life so much better—well, better in a programming sense (we can’t really help you with your fashion sense and your JavaScript skills all in one book). Just a warning: once you’ve discovered objects, you’ll never want to come back. Send us a postcard when you get there.
📄 Page 17
table of contents xv Getting to know the DOM You’ve come a long way with JavaScript. In fact, you’ve evolved from a newbie to a scripter to, well, a programmer. But, there’s something missing. To really begin leveraging your JavaScript skills, you need to know how to interact with the web page your code lives in. Only by doing that are you going to be able to write pages that are dynamic, pages that react, that respond, that update themselves after they’ve been loaded. So how do you interact with the page? By using the DOM, otherwise known as the document object model. In this chapter, we’re going to break down the DOM and show you how you can use it, along with JavaScript, to teach your pages a few new tricks. interacting with your web page 6 In the last chapter, we left you with a little challenge... 240 So what does the code do? 241 How JavaScript really interacts with your page 243 How to bake your very own DOM 244 A first taste of the DOM 245 Getting an element with getElementById 250 What, exactly, am I getting from the DOM? 251 Finding your inner HTML 252 What happens when you change the DOM 254 Don’t even think about running my code until the page is fully loaded! 259 You say “event handler,” I say “callback” 260 Why stop now? Let’s take it further 264 How to set an attribute with setAttribute 265 More fun with attributes! 266 Meanwhile, back at the solar system... 267 So what else is a DOM good for anyway? 268 document html head title body h1 h2 id=”movie1” h2 id=”movie2”p p span em meta
📄 Page 18
table of contents xvi 7 The truth is out there... 276 Watch out, you might bump into undefined... 278 How to use null 281 Dealing with NaN 283 It gets even weirder 283 We have a confession to make 285 Understanding the equality operator (otherwise known as ==) 286 How equality converts its operands 287 How to get strict with equality 290 Even more type conversions 296 How to determine if two objects are equal 299 The truthy is out there... 301 What JavaScript considers falsey 302 The Secret Life of Strings 304 How a string can look like a primitive and an object 305 How template literals work 308 A five-minute tour of string properties and methods 309 Chair Wars 314 Serious types types, equality, conversion, and all that jazz It’s time to get serious about our types. One of the great things about JavaScript is you can get a long way without knowing a lot of details of the language. But to truly master the language, get that promotion, and get on to the things you really want to do in life, you have to rock at types. Remember what we said about JavaScript back in Chapter 1? That it didn’t have the luxury of a silver-spoon, academic, peer-reviewed language definition? Well, that’s true, but the lack of an academic life didn’t stop Steve Jobs and Bill Gates, and it didn’t stop JavaScript either. It does mean that JavaScript doesn’t have the…well, the most thought-out type system, and we’ll find a few idiosyncrasies along the way. But don’t worry, in this chapter we’re going to nail all that down, and soon you’ll be able to avoid all those embarrassing moments with types.
📄 Page 19
table of contents xvii 8 Building an app Put on your toolbelt. That is, the toolbelt with all your new coding skills, your knowledge of the DOM, and even some HTML and CSS. We’re going to bring everything together in this chapter to create our first true web application. No more silly toy games with one battleship and a single row of hiding places. In this chapter, we’re building the entire experience: a nice big game board, multiple ships, and user input right in the web page. We’re going to create the page structure for the game with HTML, visually style the game with CSS, and write JavaScript to code the game’s behavior. Get ready: this is an all-out, pedal-to-the- metal development chapter where we’re going to lay down some serious code. bringing it all together This time, let’s build a REAL Battleship game 332 Stepping back...to HTML and CSS 333 Creating the HTML page: the Big Picture 334 Adding some more style 338 Using the hit and miss classes 341 Designing the game 343 Implementing the view 345 The model 350 You’re gonna need a bigger boat...and game board 351 How we’re going to represent the ships 352 Putting it all together 358 Wait, can we talk about your verbosity again? 359 A view to a kill... 361 Implementing the controller 363 Processing the player’s guess 364 Getting a player’s guess 373 How to place ships 379 Avoiding a collision! 383 Congrats, it’s startup time! 386
📄 Page 20
table of contents xviii What are events? 399 What’s an event handler? 400 Creating an event handler 401 Getting your head around events...by creating a game 404 Implementing the game 405 Let’s add some more images 410 How to reuse the same handler for all the images 412 How the event object works 415 Putting the event object to work 417 Events and queues 420 How setTimeout works 424 Finishing the image game 428 Getting asynchronous9 handling events After this chapter, you’re going to realize you aren’t in Kansas anymore. Up until now, you’ve been writing code that typically executes from top to bottom—sure, your code might be a little more complex than that, and make use of a few functions, objects, and methods, but at some point the code just runs its course. Now, we’re awfully sorry to break this to you this late in the book, but that’s not how you typically write JavaScript code. Rather, most JavaScript is written to react to events. What kind of events? Well, how about a user clicking on your page, data arriving from the network, timers expiring in the browser, changes happening in the DOM...and that’s just a few examples. In fact, all kinds of events are happening all the time, behind the scenes, in your browser. In this chapter we’re going rethink our approach to JavaScript coding, and look at how and why we should write code that reacts to events.
The above is a preview of the first 20 pages. Register to read the complete e-book.

💝 Support Author

0.00
Total Amount (¥)
0
Donation Count

Login to support the author

Login Now
Back to List