How To Check If A Property Exists In A JavaScript Object

You can use:

  • hasOwnProperty method
  • in operator
  • access the property directly
const myObject = {
games: "🎮",
numeral: 0,
anything: undefined,
};

myObject.hasOwnProperty("games") // true
myObject.toString() // [object Object], because all objects have a toString() method and [object Object] is the string representation of an object
myObject.hasOwnProperty("toString") // false, because it has the property but it comes from prototype
myObject.hasOwnProperty("numeral") // true
myObject.hasOwnProperty("anything") // true
myObject.hasOwnProperty("non-nonExisting") // false

"games" in myObject // true
"toString" in myObject // true, because it's not limited to its own properties
"anything" in myObject // true
"nonExisting" in myObject // false

/*
What people often want to do is to check whatever a property exists in order to do something.
So they use statements like these:
*/


if(myObject.games) {
// this will be evaluated
}

if(myObject["games"]) {
// this will be evaluated
}

/*
The above work because JavaScript will evaluate if the value of the property is truthy.
When the property doesn't exist it will return undefined which is falsy.
Ommiting the !== undefined check can lead to wrong behavior:
*/

if(myObject["numeral"]) {
// this won't be evaluated
}

if(myObject["anything"]) {
// this won't be evaluated
}

/** We can explicitly compare with undefined to catch all other falsy values **/
if(myObject["numeral"] !== undefined) {
// this will be evaluated
}

Tip: on Windows you can press Windows + . to open an emoji keyboard

Summary

What to use depends on your situation. Drawbacks of each:

  • hasOwnProperty: doesn't consider prototypes
  • in: considers prototypes
  • direct access: if comparing with undefined you probably should just use in or hasOwnProperty. If using without comparison than you're evaluating if property's value is truthy rather than if the property exists in the object. Check these reference for what JavaScript considers truthy and falsy