Temporal Dead Zone (TDZ) is the period of time between the creation of a [let]/[const] variable and the moment when it’s assigned a value. During this time, the variable exists but is inaccessible — trying to access it will cause a [ReferenceError]. ⚠️
console.log(x); // ReferenceError: Cannot access 'x' before initialization
let x = 5; // Only here the variable becomes accessibleImagine you ordered a pizza, but it’s not ready yet. You know it will be there, but you can’t take it — it will say “not ready yet!” This is the Temporal Dead Zone! 🍕⏰
When JavaScript sees a [let] or [const] variable, it creates it “in mind”, but doesn’t give it a value yet. The variable exists but is inaccessible:
// Temporal Dead Zone for x
console.log(x); // ❌ Error! Not yet!
let x = 5; // Now it's accessible
console.log(x); // ✅ 5JavaScript works in two phases:
// var — no Temporal Dead Zone
console.log(a); // undefined (no error)
var a = 1;
// let/const — have Temporal Dead Zone
console.log(b); // ❌ ReferenceError
let b = 2;TDZ starts at the beginning of the block and ends at the variable declaration:
{
// Start of TDZ for x
console.log(x); // ❌ Error!
let x = 10; // End of TDZ for x
console.log(x); // ✅ 10
}for (let i = 0; i < 3; i++) {
// Each iteration has its own TDZ for i
setTimeout(() => {
console.log(i); // 0, 1, 2 (works!)
});
}// ❌ Error!
console.log(name); // ReferenceError
let name = 'John';
// ✅ Correct
let name = 'John';
console.log(name); // 'John'function example() {
// TDZ for variable inside function
console.log(value); // ❌ Error!
let value = 100;
}if (true) {
// TDZ for result
console.log(result); // ❌ Error!
let result = 'done';
}// ✅ Declare first, then use
let user = 'Peter';
console.log(user); // 'Peter'// var doesn't have TDZ
console.log(message); // undefined (no error)
var message = 'hello';let globalVar = 'external';
function example() {
console.log(globalVar); // ✅ 'external'
// But not the internal variable!
// console.log(localVar); // ❌ Error!
let localVar = 'internal';
}Understanding the Temporal Dead Zone helps write code without errors and better understand how variables work in JavaScript! 💪
Want more articles to prepare for interviews? Subscribe to EasyAdvice, bookmark the site and improve yourself every day 💪