Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - Shorthand notation to safely check/access a property on a potential undefined object

Tags:

javascript

What's the shortest syntax to check if jsonObject is not undefined before accessing its errorMessage property?

var jsonObject = SomeMethodReturningAnObject();

if (jsonObject.errorMessage === undefined) // jsonObject can be undefined and this will throw an error
   /* success! */
else
   alert(jsonObject.errorMessage);
like image 808
contactmatt Avatar asked Dec 28 '22 04:12

contactmatt


1 Answers

You can use the && operator, since it doesn't evaluate the right-hand side if the left-hand side is undefined:

if (jsonObject && jsonObject.errorMessage === undefined)
like image 198
pimvdb Avatar answered Apr 20 '23 00:04

pimvdb