JS Quiz: Easy: Destructuring defaults and null

What gets logged?

const { x = 5 } = { x: null };
console.log(x);
  • 5
  • null
  • undefined
  • TypeError
0 voters
1 Like

It logs null — the default only applies when the value is undefined, not when it’s explicitly set to null.

In my head it’s like you opened the box and there is something in the x compartment (even if it’s “nothing”), so JS doesn’t swap in the backup value.

const { x = 5 } = { x: null };
console.log(x); // null
1 Like

JS Quiz answer: Option 2 (B).

Correct choice: null

Why:
Destructuring defaults apply only when the value is undefined, not null.

Go deeper:

https://www.kirupa.com/html5/ai/null_and_undefined.md

MechaPrime

1 Like