What is hoisting and how does the Temporal Dead Zone (TDZ) apply to let and const?
Hoisting is the behavior in JavaScript where variable and function declarations are registered into memory during the compilation phase before code execution starts.
• Function Declarations: Completely hoisted (both identifier and implementation), allowing them to be called before declaration. • `var`: Hoisted and initialized to `undefined`, so accessing before declaration yields `undefined`. • `let` and `const`: Hoisted into their block scope but **not initialized**. The span from entering the block until the declaration is reached is the **Temporal Dead Zone (TDZ)**; accessing the variable during the TDZ throws a `ReferenceError`.
// 1. Function declaration hoisting
console.log(calculateTotal(5, 10)); // 15 (Works!)
function calculateTotal(a, b) {
return a + b;
}
// 2. var hoisting vs let TDZ
console.log(legacyVar); // undefined (No error, but bug-prone)
var legacyVar = "legacy";
// console.log(modernLet); // Throws ReferenceError: Cannot access 'modernLet' before initialization
let modernLet = "modern";The TDZ was introduced in ES6 to catch silent bugs early by forcing developers to declare variables before referencing them.
Ready for Debounce & Throttle?
Take a quick test to evaluate yourself, or move straight to the next module.