Hoisting & the Temporal Dead Zone

Understand why JavaScript sometimes lets you use functions before you write them, and why let/const throw errors if you try the same trick.

JavaScript6 min readConcept 13 of 62

What is Hoisting?

When JavaScript compiles your code, it scans for variable and function declarations and 'hoists' (lifts) them to the top of their current scope before the code actually runs.

This is why you can call a function on line 1, even if it is not defined until line 50. The engine already knows about it!

The var trap

Historically, JavaScript only had the var keyword. When var is hoisted, the declaration goes to the top, but the *initialization* stays where it is.

This means if you try to log a var before it is initialized, you won't get an error. You will just get undefined. This led to notoriously hard-to-find bugs.

The Temporal Dead Zone (TDZ)

To fix the var trap, ES6 introduced let and const.

let and const *are* actually hoisted to the top of the block, but they are not initialized with undefined.

The zone from the top of the block down to the actual line of code where the variable is declared is called the Temporal Dead Zone (TDZ). If you try to access the variable while it is in the TDZ, JavaScript throws a ReferenceError.

The TDZ Visualizer

Toggle between a standard var declaration and a modern let declaration to see exactly how hoisting and the Temporal Dead Zone behave differently at runtime.

The TDZ Visualizer

// 1. Execution starts
Hoisted & Initialized to undefined
console.log(name);
var name = "Alice";
console.log(name);
Console OutputExecution Complete
>undefined
>"Alice"
iBecause var is hoisted and given a default value of undefined, it fails silently. This is why it is dangerous!

Check yourself

Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.

  1. 1What happens if you try to `console.log` a `var` variable before the line where it is initialized?
  2. 2What is the Temporal Dead Zone (TDZ)?
  3. 3Which of the following is fully hoisted, meaning you can call it before it is defined?

Remember this

  • Hoisting moves declarations to the top of the scope before execution.
  • Function declarations are fully hoisted.
  • var is hoisted and initialized to undefined.
  • let and const are hoisted but uninitialized, creating a Temporal Dead Zone (TDZ) that throws a ReferenceError if accessed early.

Done with this concept?

Mark it complete to track your progress. No login needed.