Jane
Jane

Reputation: 45

Destructuring fallback to prevent undefined error?

I have a list of array I do this:

const { id } = myArray.find(
        (obj) => obj === true)

If the id is not present it will throw error. How to prevent error in the same time use destructuring? I want to keep the logic in one line.

Upvotes: 4

Views: 3497

Answers (1)

norbitrial
norbitrial

Reputation: 15166

The issue here is .find() returns undefined once there is no fulfillment for the condition:

The value of the first element in the array that satisfies the provided testing function. Otherwise, undefined is returned.

So probably you can use || operator to check if you have any value returned from .find() or you can replace with empty object {} instead on the right side of the operator.

Probably the option for one-liner is the following:

const myArray = [
  { id: 12 },
  { id: 13 },
  { id: 14 }
];

const { id } = myArray.find(e => e.id === 17) || {};

console.log(id);

So you can destructure id property even if it returned undefined in this way.

Also if you need you can add default value to your destructuring statement based on the documentation which states for Destructuring statement as follows:

A variable can be assigned a default, in the case that the value unpacked from the object is undefined.

const { id = 10 } = {};

console.log(id);

I hope this helps!

Upvotes: 6

Related Questions