CodePark/ questions / Scope & hoisting
START PRACTICINGPRACTICE
Frontend question · JavaScript › Scope & hoisting

What happens when this runs?

let x = 1;
{
  console.log(x);
  let x = 2;
}
Throws a ReferenceError

The inner let x is hoisted to the top of the block. It hides (shadows) the outer x for the whole block, even on the line before it. Until its declaration runs, the inner x is in the temporal dead zone (TDZ), so console.log(x) throws a ReferenceError.

The tempting option "Logs
1" is wrong because JavaScript does not fall back to the outer x. Inside the block, the name x already means the inner variable.