Home > Enterprise >  How to check for undefined before assigning to variable
How to check for undefined before assigning to variable

Time:05-26

Im using a find method to extract an ID (string) but this is returning an undefined as it doesnt exist.

const additionalLinePhoneNumber = products.find(product => product.name === 'segundaLinea').id;

Products has the following:

(2) [ProductInventoryList, ProductInventoryList]
0: ProductInventoryList {_id: "12345", _name: "lineaFija", _productInventoryCharacteristics: ProductInventoryCharacteristics}
1: ProductInventoryList {_id: "12345", _name: "primeraLinea", _productInventoryCharacteristics: ProductInventoryCharacteristics}
length: 2

So "segundaLinea" isnt returned so the find gives me the following error:

ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'id' of undefined TypeError: Cannot read property 'id' of undefined

I tried doing this but doesnt work:

const additionalLinePhoneNumber = products.find(product => product.name === 'segundaLinea').id ? undefined : '';

What am I missing?

Trying the awnser below:

enter image description here

CodePudding user response:

You can use optional chaining like this:

const additionalLinePhoneNumber = products.find(product => product.name === 'segundaLinea')?.id;

Edit:

For Typescript, the support for optional chaining was added with the version 3.7. If you can't update your version you have to do it on multiple lines:

const segundaLinea = products.find(product => product.name === 'segundaLinea');
const additionalLinePhoneNumber = segundaLinea ? segundaLinea.id : "";

If you have to do this several times, you should probably write a helper function.

  • Related