Hoisting and Temporal Dead Zone
Implement or sketch code for Hoisting and Temporal Dead Zone. Explain the logic, complexity, and pros/cons of this approach.
Answers use simple, clear English.
Quick interview answer
Logic: var hoists and initializes undefined; let/const hoist but stay in TDZ until declaration — early access throws ReferenceError. const prevents rebinding, not deep mutation.
Detailed answer
Logic: var hoists and initializes undefined; let/const hoist but stay in TDZ until declaration — early access throws ReferenceError. const prevents rebinding, not deep mutation. Complexity notes included in code section when present. Pros: let/const reduce subtle bugs; block scope matches developer intuition. Cons: TDZ surprises in temporal code; const does not freeze object contents. Core: var hoists and initializes undefined; let/const hoist but stay in TDZ until declaration — early access throws ReferenceError. const prevents rebinding, not deep mutation. Real-time example: Loop with var captures same binding; let creates per-iteration binding in for loops. Pros: let/const reduce subtle bugs; block scope matches developer intuition. Cons: TDZ surprises in temporal code; const does not freeze object contents. Common mistakes: Assuming const makes objects immutable; using var in modern modules. Best practices: Default to const; use let when reassignment needed; never var in new code. Audience level: Architect.
Full explanation
var hoists and initializes undefined; let/const hoist but stay in TDZ until declaration — early access throws ReferenceError. const prevents rebinding, not deep mutation.
Real example & use case
Loop with var captures same binding; let creates per-iteration binding in for loops.
Pros & cons
Pros: let/const reduce subtle bugs; block scope matches developer intuition. Cons: TDZ surprises in temporal code; const does not freeze object contents.
Code example
function demo() {
// console.log(x); // ReferenceError — TDZ
let x = 1;
const cfg = { ok: true };
cfg.ok = false; // allowed
// cfg = {}; // TypeError — rebind blocked
return x;
}Practice code · javascript (view only · no execution)
function demo() {
// console.log(x); // ReferenceError — TDZ
let x = 1;
const cfg = { ok: true };
cfg.ok = false; // allowed
// cfg = {}; // TypeError — rebind blocked
return x;
}Common mistakes
Assuming const makes objects immutable; using var in modern modules.
Best practices
Default to const; use let when reassignment needed; never var in new code.
Follow-up questions
- How would you test Hoisting and Temporal Dead Zone?
- What metrics prove Hoisting and Temporal Dead Zone is healthy in prod?
- How does Hoisting and Temporal Dead Zone change at 10× traffic?