QUESTION 17 / 20 · FUNCTIONS · INTERMEDIATE

A greeting with defaults

What will this code print? Read each line, then make your prediction.

Where this matters

An optional argument can use a default when the caller omits it. A caller explicitly passing null has supplied a different value.

JavaScript · read-only example
function greet(name = 'Guest') { return `Hi ${name}`; }
console.log(greet(undefined));
console.log(greet(null));
Your prediction

Read the full explanation

An undefined argument triggers the parameter default. Null is a supplied value and becomes text during interpolation.

Trace the code

  1. The first call supplies undefined, so the default initializes name to Guest.
  2. The second call initializes name to null without applying the default.
  3. Template interpolation converts the value to text when constructing the greeting.

Why the other predictions differ

  • Hi Guest Hi Guest — Parameter defaults do not replace null.
  • Hi undefined Hi null — Undefined activates the default before the function body executes.
Expected console output
Hi Guest
Hi null

Reading this explanation does not record mastery. A correct submitted attempt can do so, including after review.

Change one thing

Omit the argument entirely and compare it with an empty string.

Predict the result, then run this self-contained snippet in your browser’s developer console. It uses only sample values and makes no network requests.

function greet(name = 'Guest') { return `Hi ${name}`; } console.log(greet()); console.log(JSON.stringify(greet('')));
Check the variation’s output
Hi Guest
"Hi "

Explain which binding, value, or operation changed before moving to the next challenge.