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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With