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?

Manu
  • 185
  • 2
  • 3
  • 13
  • Since the object is undefined, you first need to check if the object is defined before checking the value – philip yoo Mar 12 '17 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". – Manu Mar 12 '17 at 23:57
  • @Manu: don't access the property if the variable is empty or doesn't exist. – Felix Kling Mar 13 '17 at 00:06
  • For more elegant way of **checking nested object properties**, you can use a method presented by @georg in **[here](http://stackoverflow.com/a/23809123/1977012)** or see this mature post **[JavaScript test for existence of nested object key](http://stackoverflow.com/q/2631001/1977012)** – Egel Mar 13 '17 at 00:25

1 Answers1

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"});
hola
  • 3,150
  • 13
  • 21