Problem Statement
What happens when you access a let variable before its declaration?
Explanation
It throws a ReferenceError because of the Temporal Dead Zone.
The Temporal Dead Zone is the period from when you enter a scope until the variable is declared. During this time, the variable exists but you cannot access it.
Think of it like a restaurant opening:
The building exists, the sign is up, but doors are locked. You know it is there but cannot go inside yet.
Why does this exist:
JavaScript designers wanted let and const to be safer than var. The TDZ prevents you from using variables before they are initialized, which catches bugs early.
Key difference: Var is hoisted and initialized as undefined. Let and const are hoisted but stay uninitialized in the TDZ.
Code Solution
SolutionRead Only
// let and const throw errors
console.log(age); // ReferenceError: Cannot access 'age' before initialization
let age = 25;
// var behaves differently
console.log(name); // undefined (no error)
var name = 'John';
// Temporal Dead Zone explained
{
// TDZ starts here for 'temp'
// You cannot access 'temp' here
console.log(temp); // ReferenceError!
let temp = 100; // TDZ ends here
// Now you can use 'temp'
console.log(temp); // 100 - Works fine
}
// Function example
function calculate() {
// TDZ for result
// console.log(result); // Would throw error
let result = 10 * 5; // TDZ ends
console.log(result); // 50
}Practice Sets
This question appears in the following practice sets:
