codecks.

Closures & scope · Output question

JavaScript let shadowing and the temporal dead zone

A block-local let shadows an outer binding before initialization. Predict whether an early read logs a value or throws.

let amount = 4;
try {
  console.log(amount);
  let amount = 8;
} catch (error) {
  console.log(error.name);
}

What gets logged?

Choose an output before opening the walkthrough, or check your answer in practice mode.

  1. ReferenceError
  2. 4
  3. 8
  4. undefined
Reveal the answer and execution trace
ReferenceError

The inner let shadows the outer amount throughout the try block. Reading it before initialization throws.

  1. Line 2. The block has a local amount binding that is not initialized yet.
  2. Line 3. The attempted read hits that uninitialized binding, so console.log is never called here.
  3. Line 6. catch receives the exception and logs its name.

Reference: Temporal dead zone on MDN.