What gets logged?
const { x = 5 } = { x: null };
console.log(x);
- 5
- null
- undefined
- TypeError
Yoshiii
What gets logged?
const { x = 5 } = { x: null };
console.log(x);
Yoshiii
This one’s a classic “you thought it was empty but JS didn’t” trap: it logs null.
Destructuring defaults only apply when the value is undefined, so { x: null } keeps x as null instead of falling back to 5. null is basically “I meant to put nothing here,” not “missing.”
Destructuring defaults don’t rescue you from null — they only kick in when the property is actually undefined, so this logs null.
{ x: null } is “x exists and it’s intentionally empty,” whereas {} (or { x: undefined }) is “x is missing,” which is when the = 5 default applies.
Hmm
Destructuring defaults only fire on undefined, not null, so ({ x = 5 } = { x: null }) keeps x as null.
If you want null to fall back too, you need to handle it after, like x = x ?? 5.
Look — destructuring defaults are “property was undefined” handling, not “value is unusable” handling, so null just sails right through. When I want null to fall back too, I pull it out and coalesce: const { x } = obj; const safeX = x? ? 5; — keeps 0/'' intact and makes the intent obvious. not sure on that side.
When you said “null just sails right through, ” yeah that’s the part that always trips people up in quizzes — do you ever intentionally use null to mean “missing” in your codebase, or do you try to avoid it and stick to undefined? not sure about this one.
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
Yoshiii
:: Copyright KIRUPA 2024 //--