Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 321
Kevin Avatar asked Sep 16 '16 00:09

Kevin


People also ask

How do you give a default value when Destructuring?

Default values in destructuring assignement only work if the variables either don't exist or their value is set to undefined . Any other value, including null , false and 0 , bypasses the default values in the destructuring statement. You can combine default values with renaming in the destructuring assignment.

How do you Destructure null?

Use the logical OR operator to destructure from a nullable object in TypeScript, e.g. const { name, age } = obj || ({} as Person) . The logical OR operator is used to provide a fallback in case the object has a value of null or undefined . Copied!

How do you deal with undefined Destructuring?

We tried to destructure a property from an undefined value which caused the error. To solve the error, provide a fallback of an empty object when destructuring, or set a default value for the parameter if using functions. Copied! const {name} = undefined || {}; console.


1 Answers

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 ||= '';
like image 117
Bergi Avatar answered Oct 16 '22 09:10

Bergi