All sample questions / JavaScript

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

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

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

What does this print?

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

Answer, B. inner

A. undefined
Assumes the parameter is not yet assigned when the function body runs. Parameters are initialized with the arguments passed at call time before the body executes.
B. inner
Correct. The parameter x shadows the outer let x for the entire function body, so console.log prints the argument that was passed in, inner.
C. ReferenceError
Assumes naming a parameter the same as an outer variable is a conflicting redeclaration. Parameters simply shadow outer bindings, they never clash with them.
D. outer
Assumes the function reads the outer let x instead of its own parameter. A parameter named x always creates a local binding that shadows any outer variable of the same name for the whole function body.

A function parameter creates its own binding in the function scope, independent of any variable with the same name in an enclosing scope. Inside the function, every reference to that name resolves to the parameter, never to the outer variable.

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.

Previous question Next question

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