JAVASCRIPT: Check if an Object exists and is not empty

JAVASCRIPT: Check if an Object exists and is not empty

To check if an object "myObj" exists ( it's neither null nor undefined) and it's not empty we can use this expression :

myObj 
&& 
Object.keys(myObj).length !== 0  
&& 
myObj.constructor === Object

Explanation

  • myObj
    if it evaluates to true, "myObj" is neither null nor undefined ( null and undefined are falsy values)
  • Object.keys(myObj).length !== 0
    checks that "myObj" has at least one property on its own ( that is a "real" property inside the object, not a property "inherited" from the prototype chain )
  • myObj.constructor === Object
    this assures that "myObj" is indeed an object ( this is true even if myObj has been created with the literal notation)
function isObjectValid(myObj) {
  if (
    myObj &&
    Object.keys(myObj).length !== 0 &&
    myObj.constructor === Object
  ) {
    console.log("Object valid");
    } else {
    console.log("Object NOT valid");
    }
}

isObjectValid(); /* Object NOT valid */
isObjectValid(null); /* Object NOT valid */
isObjectValid(5); /* Object NOT valid */
isObjectValid(["Pikachu", "Bulbasaur"]); /* Object NOT valid */
isObjectValid(new String()); /* Object NOT valid */

isObjectValid(new Object()); /* Object NOT valid : it'an object but empty */
isObjectValid({}); /* Object NOT valid : it'an object but empty */

isObjectValid(new Object({ number: 5 })); /* Object valid */
isObjectValid({ number: 5 }); /* Object valid */