Predict the Output: The Temporal Dead Zone
What happens when foo() runs? Explain why.
function foo() {
const bar = "bar";
if (true) {
console.log(bar);
const bar = "bar1";
}
}
foo();Hints
Hint 1
let and const are hoisted to the top of their block, but they can't be read until their declaration line has run.
Solution
Show the approach
Answer: ReferenceError: Cannot access 'bar' before initialization
The inner const bar is hoisted to the top of its block but stays uninitialized until its line runs. Inside the block the name refers to the inner bar, so the outer one is shadowed and unreachable.