Temporal Dead Zone
Temporal Dead Zone (TDZ)
Section titled “Temporal Dead Zone (TDZ)”Introduction
Section titled “Introduction”The Temporal Dead Zone (TDZ) is the time between entering a scope (where a let/const variable is hoisted) and reaching the variable’s declaration. During the TDZ, accessing the variable throws a ReferenceError.
Visual Explanation
Section titled “Visual Explanation”flowchart LR A["Scope starts"] B["let x; ← TDZ starts"] C["console.log(x) → ❌ ReferenceError"] D["x = 10 ← TDZ ends"] E["console.log(x) → ✅ 10"]
A --> B B --> C C --> D D --> E
style B fill:#ff9800 style D fill:#4CAF50Why the TDZ Exists
Section titled “Why the TDZ Exists”The TDZ exists to catch programming errors early. Accessing a variable before its declaration is almost always a bug:
// Without TDZ (like var):var x = 10;function test() { console.log(x); // undefined — confusing! var x = 20;}
// With TDZ (let/const):let x = 10;function test() { console.log(x); // ReferenceError — clear error! let x = 20;}Common TDZ Scenarios
Section titled “Common TDZ Scenarios”// 1. Access before declaration{ console.log(val); // ReferenceError let val = 10;}
// 2. TDZ with typeof{ console.log(typeof val); // ReferenceError! let val = 10;}// Note: typeof with undeclared variables returns 'undefined'// But with TDZ variables, it throws!
// 3. TDZ with default parametersfunction test(x = y, y = 10) { console.log(x, y);}test(); // ReferenceError: Cannot access 'y' before initializationTDZ and Classes
Section titled “TDZ and Classes”// Classes are in the TDZconst obj = new MyClass(); // ReferenceErrorclass MyClass {}Best Practices
Section titled “Best Practices”- Declare
letandconstat the top of their scope - Never access a variable before its declaration
- Use
constby default,letwhen reassignment is needed - Avoid
typeofchecks on TDZ variables
Summary
Section titled “Summary”- TDZ: time between scope entry and variable declaration
- Accessing TDZ variables throws
ReferenceError varhas no TDZ (returnsundefined)let,const, andclassare in the TDZ- TDZ helps catch bugs early