Topic 9 of 37
TDZ
Overview
The Temporal Dead Zone is the period between entering a scope and the actual declaration of a 'let' or 'const' variable. During this zone, accessing the variable throws a ReferenceError. This was intentionally designed to catch errors caused by accessing variables before they are initialized.
Syntax
Unlike 'var' which is initialized to 'undefined' during hoisting, 'let' and 'const' remain uninitialized until their lexical binding is evaluated.
Encountering the TDZ
javascript
{
// TDZ starts here at the beginning of the block
// console.log(name); // ReferenceError: Cannot access 'name' before initialization
const name = "Alice"; // TDZ ends here
console.log(name); // "Alice"
}Common Pitfalls
- Shadowing a variable and getting confused by a ReferenceError because the inner variable's TDZ hides the outer variable.
Interview Tips
- Be ready to explain that 'let' and 'const' ARE hoisted (memory is allocated), but they are not initialized, hence the TDZ.
Real-World Example
TDZ prevents accidental usage of uninitialized state in React or Vanilla JS components.
example
javascript
function renderProfile() {
// This throws immediately instead of silently failing with 'undefined'
// updateUI(username);
const username = getUser();
updateUI(username);
}