🟑 MediumType CoercionπŸ’» Output Question

Optional chaining with nullish coalescing

πŸ’‘

Hint

?? vs ||: ?? only replaces null/undefined. || replaces any falsy (0, "", false). Use ?? when 0 or "" are valid values you want to keep.

What does this output?

const data = {
  user: {
    name: 'Alice',
    score: 0,
    address: null
  }
};

console.log(data.user?.name);
console.log(data.user?.email ?? 'no email');
console.log(data.user?.score ?? 100);
console.log(data.user?.score || 100);
console.log(data.user?.address?.city ?? 'no city');
console.log(data.org?.name ?? 'no org');

Correct Output

Alice
no email
0
100
no city
no org

Why this output?

Explanation: user.name = "Alice". email is undefined β†’ ?? "no email". score is 0 β€” ?? only replaces null/undefined, so 0 stays. score || 100 β†’ 0 is falsy β†’ 100. address is null β†’ optional chain short-circuits β†’ ?? "no city". data.org is undefined β†’ short-circuit β†’ "no org".

Key Insight: ?? vs ||: ?? only replaces null/undefined. || replaces any falsy (0, "", false). Use ?? when 0 or "" are valid values you want to keep.

More Type Coercion Output Questions

🟒 EasyLoose equality coercionβ†’πŸŸ‘ MediumAddition vs concatenationβ†’πŸŸ‘ MediumFalsy values comparisonβ†’πŸŸ‘ MediumNaN comparisonβ†’

Practice predicting output live β†’

66 output questions with instant feedback

πŸ’» Try Output Quiz