What are hoisting and the TDZ (Temporal Dead Zone)?
Practice this questionDefinition:
Hoisting is JavaScript's behavior of processing declarations before executing the code in a scope. Because of this, a function declaration can usually be called before its line appears, while variables behave differently depending on how they are declared.
The Temporal Dead Zone (TDZ) is the period from entering a scope until a let, const or class binding is initialized. The binding exists in that scope but cannot be accessed yet; trying to read it throws a ReferenceError.
Key points:
-
JavaScript sets up declarations before running that scope.
-
letandconstcannot be accessed before initialization; this period is the TDZ. -
console.log(x); let x = 1;throwsReferenceError. -
varstarts withundefined;letandconstexist in scope but cannot be read until initialized. -
A function expression follows the rules of the variable holding it; assigning an arrow function to
constdoes not make it callable early. -
Even
typeofthrows for a binding in its TDZ, unliketypeofon an undeclared name. -
Declarations are not literally moved in the source code; this describes how bindings are prepared.
Example:
console.log(a); // undefined
var a = 10;
try {
console.log(b); // Throws ReferenceError: b is in its TDZ.
let b = 20;
} catch (error) {
console.log(error.name); // ReferenceError
}var ais initialized before the first log, but its assignment to 10 happens later.bis known in its block, but reading it beforelet b = 20is not allowed.
Interview point:
- Explain both declaration setup and initialization. Saying only “variables move to the top” misses the important difference.