Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i check if an object is undefined (javascript)? [duplicate]

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?

like image 709
Manu Avatar asked Oct 18 '22 15:10

Manu


1 Answers

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"});
like image 59
hola Avatar answered Oct 21 '22 04:10

hola