DEV Community

Cover image for Want 2 Ways to Check If An Object has a Property?
Sarah Thompson
Sarah Thompson

Posted on

Want 2 Ways to Check If An Object has a Property?

It's amazing how sometimes Boolean values can turn out to be, well, not Boolean. Maybe it is true, false, null or even not there at all. And each of those four options might mean a different user flow for you to enact on the front end! So how to you check to see if that property is even in the object?

Using the hasOwnProperty() Method

This is my favorite way to determine if the property is in the object, I find it incredibly readable and straightforward. This method returns a Boolean value of true or false based on if the value is missing or not.

var coolObject= {
  title: 'SmashBrothers'
};
if(coolObject.hasOwnProperty('title'){
   console.log("It does have this property!");
}
if(coolObject.hasOwnProperty('genre'){
   //this isn't ever hit, as it returns false
}

While hasOwnProperty() is looking at property values of objects, it ignores inherited property values like toString, and only looks at the data information outlined in the object.

You can chain checks on the object together, to prevent errors in your system. Let's say that the object is being returns from an endpoint, you'll first want to check that the object in general was successfully returned, and then check if the property is there.

 if (profile && profile !== null && profile.hasOwnProperty("coolName")){
//The object exists, isn't null, and has the property "Cool Name"!
}

Using the In Operator

This method of determining if the property exists inside the object reminds me of Python in a great way. You're quite literally asking if the property is in the object. Similar to hasOwnProperty() the in operator returns a Boolean value of true or false based on if the value is missing or not from the object it is looking in.

var coolObject= {
  title: 'SmashBrothers'
};

if('title' in coolObject){    
 // true!
}
if('genre' in coolObject){
// this code won't reach because this is false
}

You're good to go!

With these two ways to check using JavaScript if a property exists in an object, you'll be ready to do all sorts of interesting user flows on your front end based off the new options of did this property get returned in the data object! Here's some more long form on the two options.

Discussion (0)