Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if sub-object exists before using it

In order to prevent using an object's value that doesn't exist (which would throw an error), I usually do something like this:

if(apple.details){
   // do something with apple.details
}

and it normally works fine. But if it's about a "object's object's value", like apple.details.price, that doesn't work, because if not even .details exists, the if() would throw an error.

What can I do or is there generally a better way to do this?

like image 240
Örom Loidl Avatar asked Aug 21 '26 07:08

Örom Loidl


1 Answers

Since 2020:

The best way to solve this is using the Optional Chaining Operator

if(apple?.details) // Undefined if apple does not exist

Suggestion of lodash is no longer required when using runtime compatible with ES2020 i.e. Most browsers today & node>14.5

like image 118
Ninad P.Chaudhari Avatar answered Aug 23 '26 21:08

Ninad P.Chaudhari



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!