2

Assuming I have a javascript object "myobject" that just contains an empty object "{}".

I ideally in my code I want to do the following:

if (theobject[keyvar][subkeyvar]) {
  // do something
}

The issue now is that because keyvar and subkeyvar do not actually exist within the object, it fails and comains that the properties are undefined. What is the simplest/least lines of code/best way to be able to do have it just "know it is undefined" and continue to execute the //do something or not without crashing?

I dont want to get too carried away with checking like:

if( keyvar in theobject ) {
   if(subkeyvar in theobject) {
        if.....
   }
}
4
  • 1
    If they both can possibly be undefined, you have to test one, then the other. Commented Mar 7, 2014 at 17:01
  • but note that those tests don't just check for undefined but also for 0, null, NaN, false and "". Commented Mar 7, 2014 at 17:03
  • if(theobject[keyvar] && theobject[keyvar][subkeyvar])? Commented Mar 7, 2014 at 17:04
  • If you're checking for existence, use in. If you're checking for a value, use === Commented Mar 7, 2014 at 17:16

5 Answers 5

1
if (typeof theobject[keyvar] !== "undefined" && typeof theobject[keyvar][subkeyvar] !== "undefined") {
  // keyvar and subkeyvar defined

}

first we check if keyvar typeof is undefined and then if subkeyvar is undefined and if they are both defined typeof theobject[keyvar] !== "undefined" && typeof theobject[keyvar][subkeyvar] !== "undefined" is true.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof

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

1 Comment

Please add an explanation.
0

you can try this :

if (theobject[keyvar] && theobject[keyvar][subkeyvar]) {

    // do something
}

Comments

0

If they both can possibly be undefined, you have to test one, then the other.

if (theobject[keyvar] && theobject[keyvar][subkeyvar]) {

This will of course fail on a key containing 0 or "" (or several other falsey but not undefined values) so you may want to use typeof on the second test.

Comments

0

Try:

if (theobject[keyvar] !== undefined && theobject[keyvar][subkeyvar] !== undefined) {
    // do something
}

Since the && operator is used, the if will not check the second value if the first value is falsey, so you will never get the 'properties are undefined` error

Comments

0
theObject.hasOwnProperty(keyvar) && theObject.hasOwnProperty[keyvar].hasOwnProperty(subkeyvar)

1 Comment

What if the property is defined in the prototype chain?

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.