During the creation phase, JavaScript moves declarations to the top of their scope (hoisting). However, variables declared with let and const exist in a 'temporal dead zone' until their declaration is reached, making them inaccessible before initialization.
Explain Hoisting and the Temporal Dead Zone (TDZ)
Use guided tracks for structured prep, then practice company-specific question sets when you want targeted interview coverage.
The Core Idea
Before JavaScript executes any code, it first scans your script to find all variable and function declarations. It sets up memory for them in a process called hoisting. But — not all declarations behave the same way.
Declaration Type | Hoisted? | Initialized Before Declaration? | Example |
|---|---|---|---|
| Yes | ✅ Initialized to |
|
| Yes | ❌ In TDZ (no access before declaration) |
|
| Yes | ❌ In TDZ (must be initialized immediately) |
|
| Yes (fully hoisted) | ✅ Can be called before definition |
|
What is Hoisting?
Hoisting means declarations are moved to the top of their scope before code runs. This doesn’t mean your code is literally moved — it’s just how JavaScript’s memory setup works during the 'creation phase' of execution.
// Example 1: var is hoisted
console.log(name); // undefined
var name = 'Alice';
// JS internally treats it like:
// var name;
// console.log(name);
// name = 'Alice';
The Temporal Dead Zone (TDZ)
For let and const, the variable exists but is not initialized yet. The time between the start of the scope and the actual declaration line is called the temporal dead zone. Accessing the variable in this zone causes a ReferenceError.
// Example 2: let and TDZ
console.log(age); // ❌ ReferenceError
let age = 25;
// In memory:
// TDZ starts → variable exists but not initialized
// Declaration reached → initialized to 25
Functions vs Variables
Function declarations are hoisted with their full definition, so you can call them before they appear. But function expressions (especially with let or const) behave like normal variables.
// Example 3: function vs expression
sayHi(); // ✅ Works
function sayHi() { console.log('Hi!'); }
sayHello(); // ❌ ReferenceError
const sayHello = function() { console.log('Hello!'); };
Common Pitfalls
- Thinking
letorconstaren’t hoisted (they are — just uninitialized). - Forgetting that accessing them early throws an error, not
undefined. - Mixing function declarations and expressions in confusing ways.
Think of it like a classroom roll call 📋. The teacher knows all students’ names at the start (hoisting), but only after they say 'here' (initialization) can they answer questions. Until then, they’re in the temporal dead zone!
- JavaScript hoists all declarations before execution.
var→ initialized asundefined.let/const→ uninitialized, causing a TDZ.functiondeclarations → fully hoisted and callable early.- Avoid referencing variables before their declaration line.