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: '' }
const { email = '' } = person
// email is ''

// #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?

1

1 Answer

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 ||= '';
10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Maya Lin-Takahashi

Maya Lin-Takahashi

Consumer Tech & Gadget Reviewer

Maya is a hardware enthusiast who tests and reviews smart home devices, smartphones, wearables, and audio gear. She focuses on practical consumer value and build quality.

Share this article
Twitter Facebook Pinterest