5

My goal: Test if the attribute of an object is/returns true. However, in some cases, the object is undefined.


This works no problem. The script continues normally.

if(somethingUndefined){ }


However, if I try to access an attribute of an undefined object, this generates an error and stops the script.

if(somethingUndefined.anAttribute){ }


Right now, this is what I'm using to solve the problem:

if(somethingUndefined && somethingUndefined.anAttribute){ }


Is there another way to do that? Maybe a global settings that will return false if the program tries to access an attribute of an undefined object?

2
  • 1
    somethingUndefined && somethingUndefined.anAttribute is a standard practice Commented Sep 3, 2013 at 3:39
  • I'd love it if we could check nested properties without getting fatal errors. Working with the WP API atm and my code looks like this all over the place; if (this.post.featured_image && this.post.featured_image.media_details && this.post.featured_image.media_details.sizes && this.post.featured_image.media_details.sizes.large) Commented Sep 22, 2017 at 10:50

3 Answers 3

1

If you have many if statement like if(somethingUndefined && somethingUndefined.anAttribute){ }, then you could assign an empty object to it when it is undefined.

var somethingUndefined = somethingUndefined || {};

if (somethingUndefined.anAttribute) {

}
Sign up to request clarification or add additional context in comments.

Comments

1

You can take advantage of JavaScript's ability to assign variables within if conditions and follow this pattern for faster checks once you get past the first nested object.

JsPerf

var x; 
if(
   (x = somethingUndefined) && // somethingUndefined exists?
   (x = x.anAttribute) && // x and anAttribute exists?
   (x = x.subAttrubute) // x and subAttrubute exists?
){

}

vs the traditional

if(
    somethingUndefined && // somethingUndefined exists?
    somethingUndefined.anAttribute && // somethingUndefined and anAttribute exists?
    somethingUndefined.anAttribute.subAttribute // somethingUndefined and anAttribute and subAttribute exists?
){

}

Comments

0

The way you have it in your question is generally the way it's done in javascript. If you find yourself using this a lot, you could abstract it out into a function to make things a tiny bit cleaner for yourself, as such:

if (attrDefined(obj, 'property')) {
  console.log('it is defined, whoo!');
}

function attrDefined(o, p){ return !!(o && o[p]) }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.