5

I have to check if a object is undefined but when i do

typeof myUnexistingObject.myUnexistingValue == 'undefined'

i get this error

Uncaught ReferenceError: myUnexistingObject is not defined

so, how can I check for undefined obects or properties?

4
  • Since the object is undefined, you first need to check if the object is defined before checking the value Commented Mar 12, 2017 at 23:53
  • Hmm i tried to check the undefined object, if it is not undefined i have to check if it has some undefined values but i got an error, " Cannot read property 'original' of undefined". Commented Mar 12, 2017 at 23:57
  • @Manu: don't access the property if the variable is empty or doesn't exist. Commented Mar 13, 2017 at 0:06
  • For more elegant way of checking nested object properties, you can use a method presented by @georg in here or see this mature post JavaScript test for existence of nested object key Commented Mar 13, 2017 at 0:25

1 Answer 1

3

You must check for each potentially defined property before using it:

function checkUnexistingObject(myUnexistingObject) {
  if (myUnexistingObject !== undefined) {
    if (myUnexistingObject.otherObject !== undefined) {
      console.log("All is well");
    }
  }
}
checkUnexistingObject({});
checkUnexistingObject({otherObject: "hey"});

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

6 Comments

That will still throw an error in the OP's case, since myUnexisistingObject isn't even declared.
I don't think op said that myUnexistingObject wasn't declared.
But the error they are getting says that.
Okay, I know what you mean, but declared !== defined.
Sure. I'm just saying that the OP would get exactly the same error with your solution.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.