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.
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
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
- Hoisting moves declarations to the top of the scope before execution.
- Function declarations are fully hoisted.
varis hoisted and initialized toundefined.letandconstare 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.