All sample questions / JavaScript

JavaScript Scope, Hoisting and Closures, what does console.log(x) print after let x = 'outer'?

Block 2, Scope, Hoisting and Closures, question 1 of the JavaScript sample

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

What does this print?

  1. A. undefined
  2. B. outer
  3. C. inner
  4. D. ReferenceError
Show the answer and why each option is right or wrong

Answer, C. inner

A. undefined
Assumes the inner declaration is hoisted without its assignment, similar to a var mistake, and read before being set. The assignment happens on the same line as the declaration, so the log already sees the initialized value.
B. outer
Assumes the inner block reuses the outer binding instead of creating its own. A block introduces a new scope, so the inner let x is a completely separate variable that shadows the outer one inside the block.
C. inner
Correct. The inner block creates its own scope with a new x that shadows the outer one, so the console.log inside the block prints the inner value.
D. ReferenceError
Assumes redeclaring x inside a nested block conflicts with the outer declaration. Shadowing in a separate block is legal, only redeclaring in the exact same block scope would throw.

Curly braces alone create a new block scope for let and const declarations. A let declared inside that block shadows any variable of the same name from an outer scope for the rest of the block, without affecting the outer binding at all.

The answer above is what the Node interpreter printed when the snippet was run, not what someone expected it to do.

This question comes from a bank of 600 JavaScript interview questions, all built the same way, sold as one PDF with the full answer key.

Get the 600 JavaScript questions, 9 euros

Or play the free JavaScript sample, twenty questions in the browser, also as a free PDF.

Next question

Did this save you a lookup? Buy me a coffee on Ko-fi.