DerZyklop
DerZyklop

Reputation: 3823

Searching for a better solution than folded if statements for undefined properties of an object

This is a very basic issue about if statements. It doesn’t necessarily effect only javascript.

If object.user is undefined this will break:

if ( object.user.name ) {
  sayMyName();
} else {
  object.user = {};
  object.user.name = 'Jane Doe';
  sayMyName();
}

because it can not read a property of undefined. So i put the else stuff in a function and folded the if into another if:

function anonymous(object) {
  object.user = {};
  object.user.name = 'Jane Doe';
  sayMyName();
}

if ( object.user ) {
  if ( object.user.name ) {
    sayMyName();
  } else {
    anonymous();
  }
} else {
  anonymous();
}

But this looks like bad code to me. This case must be a common problem. Or at least i have it quite often. Is there any good solution for this?

EDIT:

@Mritunjay's proposal

if(object && object.user && object.user.name){...}

is way better, but it doesn’t seem to be the best solution. Imagine a if-statements that tries to get obj.some.very.very.deep.property. I‘m currently trying to write a helper-function like checkPropertySafely(object.user.name); that goes back to object, and checks every property recursively, no matter how deep it is. So basically i try to automate @Mritunjay’s manually written statement.

Upvotes: 2

Views: 66

Answers (2)

DerZyklop
DerZyklop

Reputation: 3823

I finally figured out how to write the helper-function. Here it is:

function propertyExists(property) {
    var statement = '';
    var prevItem = '';

    property.split(".").forEach(function(item, index) {
        if (index != 0) {statement += ' && '}
        statement += prevItem+item;
        prevItem += item+'.';
    });

    return eval(statement);
}

With this function, i can now simply do this:

if ( propertyExists('object.user.name') ) {
  sayMyName();
} else {
  anonymous();
}

Upvotes: 0

Mritunjay
Mritunjay

Reputation: 25892

I use bellow in this situation

if(object.user && object.user.name){...}

BTW you should check if object also exists.

if(object && object.user && object.user.name){...}

Upvotes: 2

Related Questions