whatstheoutput_

#85: let x in a nested block

Topic: scope · Difficulty: ★

let x = 'outer';
{
  let x = 'inner';
  console.log(x);
}
console.log(x);

Output

inner
outer

Why

A bare pair of curly braces creates its own block scope for let and const (even with no if, for, or function attached to it). The inner `let x = 'inner'` declares a completely new, separate binding that only exists within that block — it shadows the outer x rather than reassigning it. Inside the block, console.log(x) resolves to the closest x in scope, the inner one, printing 'inner'. Once execution leaves the block, that inner x is gone entirely, and the outer x — untouched the whole time — is what the second console.log sees: 'outer'.

More scope puzzles

Play today's puzzle →