Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

In JavaScript, how can I conditionally assign value to object with destructuring and short circuit evaluation?

Let’s say I have this set up:

const objA = { name: "Jacob", email: "jacob@email.com" };
const objB = { lastName: "Smith" };

Why can I do this:

const lastName = objA.lastName || objB.lastName;

But not this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const { lastName } = objA || objB;

Was able to re-create above example in dev tools.

My real world application: I have "normal" and "legacy" account roles, and after querying both types of roles, I’d like to be able to do:

const { schoolAdmin } = account || legacyAccount;

… but instead have to do:

const schoolAdmin = account.schoolAdmin || legacyAccount.schoolAdmin;

Which is admittedly not a big deal, but I feel like there’s something I’m missing and that I could use destructuring here. Jr dev, sorry if this is a dummy question!
(Sometimes there is no account, and sometimes there is an account that doesn’t have the schoolAdmin role! Likewise with legacyAccount.)

>Solution :

As explained in the comments || doesn’t evaluate to union of objects, it returns the second one

You can do this instead:

const { lastName } = { ...objA, ...objB };

It does create a union

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading