48

Variable and Function Hoisting

In this Chapter

  • Understand the relationship between when a variable is declared, initialized, and used

  • Impress your friends with knowledge about the temporal dead zone, a source of many a gnarly error!

One of the quirkiest things about JavaScript is this thing known as hoisting. We’ll get to what it means in a bit, but let’s set the stage for it by looking at some examples and figuring out what the right behavior should be. For our first example, take a look at the following code:

function foo() {
  return "Yay!";
}
 
console.log(foo());

What do you think is going to be displayed in our console when this code runs? Here are three choices:

  1. undefined

  2. Error—foo isn’t referenced

  3. Yay!

If you guessed Yay!, you ...

Get Javascript Absolute Beginner's Guide, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.