Hoisting

Grade 9, page 8 of 11. A two-minute read.

Here's a strange one. Look at this code, which calls a function before it's defined:

JavaScript
sayHello();

function sayHello() {
  console.log("Hello from the future! 👋");
}

It prints

Hello from the future! 👋

How does that work? JavaScript hasn't reached the function definition yet!

The answer is a behavior called hoisting. Before running your code, JavaScript does a quick first pass, scanning through each scope and setting up all the variables and function declarations it finds. It's as if they were "hoisted" (lifted) to the top of their scope.

Different kinds of declarations are hoisted differently:

DeclarationHoisted?Can you use it before the line it's on?
function name() {}Yes, completely✅ Yes, it works fine
var x = 5Yes, but without its value⚠️ Sort of: it's undefined
let x = 5 / const x = 5Yes, but locked❌ No: ReferenceError
JavaScript
console.log(oldSchool);
var oldSchool = "var";

It prints

undefined

With var, the variable exists from the start of its scope, but its value isn't assigned until JavaScript reaches that line. So you get a silent undefined. That's dangerous, because it hides your mistake.

JavaScript
console.log(modern);
let modern = "let";

It stops with an error

Uncaught ReferenceError: Cannot access 'modern' before initialization

With let and const, JavaScript knows the variable exists, but refuses to let you touch it until its line has run. The stretch of code between the start of the scope and the declaration is nicknamed the temporal dead zone (which sounds like a sci-fi movie, but is really just "the part where you're not allowed to use it yet"). This is much better: instead of a silent undefined, you get a loud, clear error.

TipThe simple rule

You don't need to memorize all of hoisting's details. Just follow this habit, and it will never bite you: create your variables before you use them. Function declarations are the one exception, and it's fine to put helper functions at the bottom of a file if you like that style.

Reading is step one

CurlyScript turns these notes into a game: short questions, an explanation after every answer, and a test at the end of each grade. Free, with nothing to sign up for.

Start learning