Variable Declarations: var vs let vs const & Temporal Dead Zone (TDZ)
1Concept
var is function-scoped and hoisted with undefined. let and const are block-scoped {} and hoisted into the Temporal Dead Zone (TDZ), throwing ReferenceError if accessed before declaration.
2Architecture Diagram
Scope Entry {
[ Temporal Dead Zone (TDZ) - accessing let/const throws ReferenceError ]
let x = 10; // Initialization ends TDZ
// Accessible here
}3Code Example
Stage 0 Language Foundations
function scopeDemo() {
if (true) {
var functionScoped = "I leak out of if-blocks!";
let blockScoped = "I am contained inside this block!";
const immutableRef = { score: 100 };
immutableRef.score = 200; // Mutating object property is ALLOWED
}
console.log(functionScoped);
// console.log(blockScoped); -> ReferenceError!
}
scopeDemo();4Expected Output
I leak out of if-blocks!
5Key Takeaways
- ✓Default to const; use let only when variable reassignment is required.
- ✓Never use var in modern JavaScript.
- ✓const objects can still have their properties mutated.