Head First JavaScript Programming

Book description

What will you learn from this book?

This brain-friendly guide teaches you everything from JavaScript language fundamentals to advanced topics, including objects, functions, and the browser’s document object model. You won’t just be reading—you’ll be playing games, solving puzzles, pondering mysteries, and interacting with JavaScript in ways you never imagined. And you’ll write real code, lots of it, so you can start building your own web applications. Prepare to open your mind as you learn (and nail) key topics including:

  • The inner details of JavaScript
  • How JavaScript works with the browser
  • The secrets of JavaScript types
  • Using arrays
  • The power of functions
  • How to work with objects
  • Making use of prototypes
  • Understanding closures
  • Writing and testing applications

What’s so special about this book?

We think your time is too valuable to waste struggling with new concepts. Using the latest research in cognitive science and learning theory to craft a multi-sensory learning experience, Head First JavaScript Programming uses a visually rich format designed for the way your brain works, not a text-heavy approach that puts you to sleep. This book replaces Head First JavaScript, which is now out of print.

Publisher resources

View/Submit Errata

Table of contents

  1. Head First JavaScript Programming
  2. Dedication
  3. Praise for Head First JavaScript Programming
  4. Praise for other books by Eric T. Freeman and Elisabeth Robson
  5. Authors of Head First JavaScript Programming
  6. How to Use This Book: Intro
    1. Who is this book for?
      1. Who should probably back away from this book?
    2. We know what you’re thinking.
      1. And we know what your brain is thinking.
    3. Metacognition: thinking about thinking
    4. Here’s what WE did:
    5. Here’s what YOU can do to bend your brain into submission
    6. Read Me
    7. Tech Reviewers
    8. Acknowledgments
  7. 1. Getting your feet wet
    1. The way JavaScript works
    2. How you’re going to write JavaScript
    3. How to get JavaScript into your page
      1. A little test drive
    4. JavaScript, you’ve come a long way baby...
      1. It’s True.
    5. How to make a statement
    6. Variables and values
    7. Back away from that keyboard!
    8. Express yourself
    9. Doing things more than once
    10. How the while loop works
    11. Making decisions with JavaScript
    12. And, when you need to make LOTS of decisions
    13. Reach out and communicate with your user
      1. Create an alert.
      2. Write directly into your document.
      3. Use the console.
      4. Directly manipulate your document.
    14. A closer look at console.log
    15. Opening the console
    16. Coding a Serious JavaScript Application
    17. How do I add code to my page? (let me count the ways)
    18. We’re going to have to separate you two
  8. 2. Going further
    1. Let’s build a Battleship game
    2. Our first attempt...
    3. First, a high-level design
    4. A few more details...
      1. Representing the ships
      2. Getting user input
      3. Displaying the results
    5. Working through the Pseudocode
    6. Oh, before we go any further, don’t forget the HTML!
    7. Writing the Simple Battleship code
    8. Now let’s write the game logic
    9. Step One: setting up the loop, getting some input
    10. How prompt works
    11. Checking the user’s guess
    12. So, do we have a hit?
    13. Adding the hit detection code
    14. Hey, you sank my battleship!
    15. Provide some post-game analysis
    16. And that completes the logic!
    17. Doing a little Quality Assurance
    18. Can we talk about your verbosity...
    19. Finishing the Simple Battleship game
    20. How to assign random locations
    21. The world-famous recipe for generating a random number
    22. Back to do a little more QA
    23. Congrats on your first true JavaScript program, and a short word about reusing code
  9. 3. Getting functional
    1. What’s wrong with the code anyway?
    2. By the way, did we happen to mention FUNCTIONS?
    3. Okay, but how does it actually work?
    4. What can you pass to a function?
    5. JavaScript is pass-by-value.
      1. That means pass-by-copy.
    6. Weird Functions
      1. EXPERIMENT #1: what happens when we don’t pass enough arguments?
      2. EXPERIMENT #2: what happens when we pass too many argments?
      3. EXPERIMENT #3: what happens when we have NO parameters?
    7. Functions can return things too
    8. Tracing through a function with a return statement
    9. Global and local variables
      1. Know the difference or risk humiliation
    10. Knowing the scope of your local and global variables
    11. The short lives of variables
    12. Don’t forget to declare your locals!
  10. 4. Arrays
    1. Can you help Bubbles-R-Us?
    2. How to represent multiple values in JavaScript
    3. How arrays work
      1. How to create an array
    4. How to access an array item
    5. Updating a value in the array
    6. How big is that array anyway?
    7. The Phrase-O-Matic
    8. Meanwhile, back at Bubbles-R-Us...
      1. Cubicle Conversation
    9. How to iterate over an array
    10. But wait, there’s a better way to iterate over an array
      1. Test drive the bubble report
    11. It’s that time again.... Can we talk about your verbosity?
    12. Redoing the for loop with the post-increment operator
    13. Quick test drive
      1. Cubicle Conversation Continued...
    14. Creating an array from scratch (and adding to it)
      1. Test drive the final report
    15. And the winners are...
    16. A quick survey of the code...
    17. Writing the printAndGetHighScore function
    18. Refactoring the code using printAndGetHighScore
    19. Putting it all together...
  11. 5. A trip to Objectville
    1. Did someone say “Objects”?!
    2. Thinking about properties...
    3. How to create an object
    4. What is Object-Oriented Anyway?
    5. How properties work
    6. How does a variable hold an object? Inquiring minds want to know...
    7. Comparing primitives and objects
      1. Initializing a primitive variable
      2. Initializing an object (a reference) variable
    8. Doing even more with objects...
      1. Doing some pre-qualification
      2. Does the taxi cut it?
    9. Stepping through pre-qualification
    10. Let’s talk a little more about passing objects to functions
      1. Putting Fido on a diet....
      2. The Auto-O-Matic
    11. Oh Behave! Or, how to add behavior to your objects
    12. Improving the drive method
      1. Take the fiat for a test drive
      2. Uh oh, not so fast...
    13. Why doesn’t the drive method know about the started property?
      1. A test drive with “this”
    14. How this works
    15. How behavior affects state... Adding some Gas-o-line
    16. Now let’s affect the behavior with the state
      1. Gas up for a test drive
    17. Congrats on your first objects!
    18. Guess what? There are objects all around you! (and they’ll make your life easier)
  12. 6. Getting to know the DOM
    1. In our last chapter, we left you with a little challenge. The “crack the code challenge.”
    2. So what does the code do?
      1. A quick recap
    3. How JavaScript really interacts with your page
    4. How to bake your very own DOM
    5. A first taste of the DOM
    6. Getting an element with getElementById
    7. What, exactly, am I getting from the DOM?
    8. Finding your inner HTML
    9. What happens when you change the DOM
    10. A test drive around the planets
    11. Don’t even think about running my code until the page is fully loaded!
      1. Let’s try that again...
    12. You say “event handler,” I say “callback”
      1. Why stop now? Let’s take it further
    13. How to set an attribute with setAttribute
    14. More fun with attributes! (you can GET attributes too)
      1. What happens if my attribute doesn’t exist in the element?
      2. Meanwhile, back at the solar system...
      3. Test driving the planets one last time...
    15. So what else is a DOM good for anyway?
  13. 7. Serious types
    1. The truth is out there...
    2. Watch out, you might bump into undefined when you aren’t expecting it...
    3. How to use null
    4. Dealing with NaN
    5. It gets even weirder
    6. We have a confession to make
    7. Understanding the equality operator (otherwise known as ==)
      1. If the two values have the same type, just compare them
      2. If the two values have different types, try to convert them into the same type and then compare them
    8. How equality converts its operands (sounds more dangerous than it actually is)
      1. CASE#1: Comparing a number and a string.
      2. CASE#2: Comparing a boolean with any other type.
      3. CASE#3: Comparing null and undefined.
      4. CASE#4: Oh, actually there is no case #4.
    9. How to get strict with equality
      1. Two values are strictly equal only if they have the same type and the same value.
    10. Even more type conversions...
      1. Another look at concatenation, and addition
      2. What about the other arithmetic operators?
    11. How to determine if two objects are equal
      1. When we test equality of two object variables, we compare the references to those objects
      2. Two references are equal only if they reference the same object
    12. The truthy is out there...
    13. What JavaScript considers falsey
    14. The Secret Life of Strings
    15. How a string can look like a primitive and an object
    16. A five-minute tour of string methods (and properties)
    17. Chair Wars (or How Really Knowing Types Can Change Your Life)
      1. In Larry’s cube
      2. In Brad’s cube
      3. But wait! There’s been a spec change
      4. Back in Larry’s cube
      5. At Brad’s laptop at the beach
      6. Larry snuck in just ahead of Brad.
      7. The suspense is killing me. Who got the chair?
  14. 8. Building an app
    1. This time, let’s build a REAL Battleship game
    2. Stepping back... to HTML and CSS
    3. Creating the HTML page: the Big Picture
      1. Step 1: The Basic HTML
      2. Step 2: Creating the table
      3. Step 3: Player interaction
    4. Adding some more style
      1. Step 4: Placing the hits and misses
    5. Using the hit and miss classes
    6. How to design the game
    7. Implementing the View
    8. How displayMessage works
      1. Implementing displayMessage
    9. How displayHit and displayMiss work
      1. Implementing displayHit and displayMiss
      2. Another Test Drive...
    10. The Model
      1. How the model interacts with the view
      2. You’re gonna need a bigger boat... and game board
    11. How we’re going to represent the ships
    12. Implementing the model object
      1. Thinking about the fire method
    13. Setting up the fire method
      1. Looking for hits
      2. Putting that all together...
      3. Wait, can we talk about your verbosity again?
      4. Meanwhile back at the battleship...
      5. A view to a kill...
    14. Implementing the Controller
    15. Processing the player’s guess
    16. Planning the code...
    17. Implementing parseGuess
      1. Meanwhile back at the controller...
    18. Counting guesses and firing the shot
      1. Game over?
      2. Getting a player’s guess
    19. How to add an event handler to the Fire! button
      1. Getting the player’s guess from the form
    20. Passing the input to the controller
      1. What’s left? Oh yeah, darn it, those hardcoded ships!
    21. How to place ships
      1. The generateShipLocations function
    22. Writing the generateShip method
    23. Generate the starting location for the new ship
    24. Completing the generateShip method
      1. Avoiding a collision!
      2. Two final changes
      3. Congrats, It’s Startup Time!
  15. 9. Handling events
    1. What are events?
    2. What’s an event handler?
    3. How to create your first event handler
    4. Test drive your event
    5. Getting your head around events... by creating a game
    6. Implementing the game
      1. Step 1: access the image in the DOM
      2. Step 2: add the handler, and update the image
    7. Test drive
    8. Let’s add some more images
    9. Now we need to assign the same event handler to each image’s onclick property
    10. How to reuse the same handler for all the images
      1. Assigning the click handler to all images on the page
    11. How the event object works
    12. Putting the event object to work
    13. Test drive the event object and target
    14. Events and queues
    15. Even more events
      1. Test drive your timer
    16. How setTimeout works
    17. Finishing the image game
    18. Test driving the timer
  16. 10. Liberated functions
    1. The mysterious double life of the function keyword
    2. Function declarations versus function expressions
    3. Parsing the function declaration
    4. What’s next? The browser executes the code
    5. Moving on... The conditional
      1. And finishing up...
    6. How functions are values too
    7. Did we mention functions have First Class status in JavaScript?
    8. Flying First Class
    9. Writing code to process and check passengers
    10. Iterating through the passengers
    11. Passing a function to a function
      1. Test drive flight
    12. Returning functions from functions
    13. Writing the flight attendant drink order code
    14. The flight attendant drink order code: a different approach
      1. Wait, we need more drinks!
    15. Taking orders with first class functions
      1. Test drive flight
    16. Webville Cola
    17. How the array sort method works
    18. Putting it all together
      1. Meanwhile back at Webville Cola
    19. Take sorting for a test drive
  17. 11. Serious functions
    1. Taking a look at the other side of functions...
    2. How to use an anonymous function
    3. We need to talk about your verbosity, again
    4. When is a function defined? It depends...
    5. What just happened? Why wasn’t fly defined?
    6. How to nest functions
    7. How nesting affects scope
    8. A little review of lexical scope
    9. Where things get interesting with lexical scope
    10. Functions Revisited
    11. Calling a function (revisited)
    12. What the heck is a closure?
    13. Closing a function
    14. Using closures to implement a magic counter
      1. Test drive your magic counter
    15. Looking behind the curtain...
    16. Creating a closure by passing a function expression as an argument
    17. The closure contains the actual environment, not a copy
    18. Creating a closure with an event handler
      1. Click me! without a closure
      2. Click me! with a closure
      3. Test drive your button counter
    19. How the Click me! closure works
  18. 12. Creating objects
    1. Creating objects with object literals
    2. Using conventions for objects
    3. Introducing Object Constructors
    4. How to create a Constructor
    5. How to use a Constructor
    6. How constructors work
    7. You can put methods into constructors as well
      1. Take the bark method for a quick test drive
    8. It’s Production Time!
    9. Let’s test drive some new cars
    10. Don’t count out object literals just yet
    11. Rewiring the arguments as an object literal
    12. Reworking the Car constructor
    13. Understanding Object Instances
    14. Even constructed objects can have their own independent properties
    15. Real World Constructors
    16. The Array object
    17. Even more fun with built-in objects
  19. 13. Extra strength objects
    1. Hey, before we get started, we’ve got a better way to diagram our objects
    2. Revisiting object constructors: we’re reusing code, but are we being efficient?
    3. Is duplicating methods really a problem?
    4. What are prototypes?
    5. Inheriting from a prototype
    6. How inheritance works
    7. Overriding the prototype
      1. So where do you get a prototype?
    8. How to set up the prototype
      1. Test drive the prototype with some dogs
      2. Give Spot his WOOF! in code
      3. Test drive the custom bark method
      4. Teaching a new trick
    9. Prototypes are dynamic
    10. A more interesting implementation of the sit method
      1. Test drive the new sit method
    11. One more time: how the sitting property works
    12. How to approach the design of the show dogs
    13. Setting up a chain of prototypes
    14. How inheritance works in a prototype chain
    15. Creating the show dog prototype
      1. First, we need an object that inherits from the dog prototype
      2. Next, turning our dog instance into a show dog prototype
      3. Now it’s time to fill in the prototype
    16. Creating a show dog instance
      1. Test drive the show dog
      2. Examining the exercise results
    17. A final cleanup of show dogs
      1. A little more cleanup
    18. Stepping through Dog.call
      1. The final test drive
    19. The chain doesn’t end at dog
      1. What is Object?
      2. Object as a prototype
    20. Using inheritance to your advantage... by overriding built-in behavior
    21. Using inheritance to your advantage... by extending a built-in object
      1. Test driving the cliché machine
    22. Grand Unified Theory of
    23. Better living through objects
    24. Putting it all together
    25. What’s next?
  20. A. Leftovers: The top ten topics (we didn’t cover)
    1. #1 jQuery
    2. #2 Doing more with the DOM
    3. #3 The Window Object
    4. #4 Arguments
    5. #5 Handling exceptions
      1. Try/catch
    6. #6 Adding event handlers with addEventListener
      1. Event handling in IE8 and older
    7. #7 Regular Expressions
      1. The RegExp constructor
      2. Using a RegExp object
    8. #8 Recursion
    9. #9 JSON
    10. #10 Server-side JavaScript
  21. Index
  22. About the Authors
  23. Colophon
  24. Copyright

Product information

  • Title: Head First JavaScript Programming
  • Author(s): Eric T. Freeman, Elisabeth Robson
  • Release date: March 2014
  • Publisher(s): O'Reilly Media, Inc.
  • ISBN: 9781449343989