Course contentsShow
← JavaScript
Lesson 95 of 2,7233. Variables and ScopeFree lesson

Common TDZ Pitfalls

Gotchas like typeof checks, nested scopes, and default parameters that can trigger TDZ errors.

Common TDZ Pitfalls

You'll learn the most common ways developers accidentally trigger Temporal Dead Zone errors, even when they think their code is safe.

The Sneaky Nature of TDZ

You've seen how let and const create a TDZ from the start of their scope until initialization. Now let's explore the tricky situations where TDZ errors catch developers off guard, even when the problematic code looks correct at first glance.

typeof in the TDZ

Normally, typeof never throws errors—even for undeclared variables. But in the TDZ, it does:

console.log(typeof undeclaredVariable);  // "undefined" (no error)
console.log(typeof myVar);                // ReferenceError!
let myVar = 10;

The first typeof works because undeclaredVariable truly doesn't exist. The second fails because myVar does exist in the TDZ.

Nested Scope Traps

Variables in outer scopes can be shadowed, creating unexpected TDZ zones:

let name = "Outer";

{
  console.log(name);  // ReferenceError!
  let name = "Inner"; // Shadows outer 'name'
}

You might expect "Outer" to print, but the inner let name creates its own TDZ for the entire block, even before its declaration line.

Function Calls in the TDZ

Functions called during initialization can't access variables in their own TDZ:

function getValue() {
  return multiplier * 2;  // ReferenceError!
}

let result = getValue();
let multiplier = 5;

The function runs before multiplier is initialized.

Key Takeaway: The TDZ applies to the entire scope from its start, affects typeof, respects shadowing in nested blocks, and includes any code that executes before the declaration line—even function calls.