'destructuring falsy and null with default parameters

I'm trying to understand how falsy and null values are destructured with default parameters. Here are some examples I've ran:

// #1
const person = { email: '[email protected]' }
const { email = '' } = person
// email is '[email protected]'

// #2
const person = { email: '' }
const { email = '' } = person
// email is ''

// #3
const person = { email: false }
const { email = '' } = person
// email is boolean false.  why?!

// #4
const person = { email: null }
const { email = '' } = person
// email is null.  why?!

Is there a shortcut I could write to destructure falsy and null values for #3 and #4 so that my email is an empty string?



Solution 1:[1]

Only undefined will cause the default initialiser to run in destructuring and function parameter targets. If you want to fall back to your default for all falsy values, use the good old || operator instead:

const email = person.email || '';

Or target a mutable variable and use logical OR assignment afterwards:

let { email } = person;
email ||= '';

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1