5

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);
contactmatt
  • 18,116
  • 40
  • 128
  • 186

5 Answers5

6

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)
pimvdb
  • 151,816
  • 78
  • 307
  • 352
4

Another way to do this is to use the typeof operator.

In JS if a variable has been declared but not set a value, such as: var x;

Then x is set to undefined so you can check for it easily by:

if(x) //x is defined
if(!x) //x is undefined

However if you try to do if(x) on a variable that hasn't even been declared, you'll get the error you allude to in your post, "ReferenceError: x is not defined".

In this case we need to use typeof - MSDN Docs - to check.

So in your case something like:

if(typeof jsonObject !== "undefined") {
    //jsonObject is set
    if(jsonObject.errorMessage) {
        //jsonObject set, errorMessage also set
    } else {
        //jsonObject set, no errorMessage!
    }
} else {
    //jsonObject didn't get set
}

This works because if you have a variable set to an empty object, x={}, and try to get at a variable within that object that doesn't exist, eg x.y, you get undefined returned, you don't get a ReferenceError.

Be aware that the typeof operator returns a string denoting the variable type, not the type itself. So it would return "undefined" not undefined.

Also, this very similar question on SO that could help you: How to check a not-defined variable in JavaScript

Hope this helps.

Jack.

Community
  • 1
  • 1
Jack Franklin
  • 3,765
  • 6
  • 26
  • 34
1
var jsonObject = SomeMethodReturningAnObject();

if (jsonObject && jsonObject.errorMessage === undefined)
   /* success! */
else
   alert(!jsonObject ? "jsonObject not defined" : jsonObject.errorMessage);
nicosantangelo
  • 13,216
  • 3
  • 33
  • 47
0

I'll answer the shorthand notation aspect as your specific situation is better served by an existing answer. As of ECMAScript 2018 we have spread syntax, which makes the whole thing much more concise:


if ( {...jsonObject}.errorMessage ) {
    // we have errorMessage
} else {
    // either jsonObject or jsonObject.errorMessage are undefined / falsey
    // in either case, we don't get an exception
}

A straight if / else is not the perfect fit for your situation because you actually have 3 states, 2 of which are crammed into the same if branch above.

  1. No jsonObject: Failure
  2. Has jsonObject, has no errorMessage: Success
  3. Has jsonObject, has errorMessage: Failure

Why this works:

Accessing a property foo from an object obj, assuming the object is undefined, is essentially doing this:

undefined.foo //exception, obviously

Spread syntax copies properties to a new object, so you end up with an object no matter what:

typeof {...undefined} === 'object'

So by spreading obj you avoid operating directly on a potentially undefined variable.

Some more examples:

({...undefined}).foo  // === undefined, no exception thrown

({...{'foo': 'bar'}}).foo // === 'bar'
rath
  • 3,655
  • 1
  • 40
  • 53
0
if(jsonObject)
{
    if (!jsonObject.errorMessage)
        // success..
        foo()    
    else
        alert(jsonObject.errorMessage);
}
gdoron
  • 147,333
  • 58
  • 291
  • 367