Checking for Existence of Object Properties in Javascript

Elisheva Elbaz
Level Up Coding
Published in
2 min readNov 2, 2020

--

Photo by Kristopher Roller on Unsplash

I recently had a mock technical interview through Skilled where I was paired with an interviewer and given code challenges in Javascript and React.

Part of my solution to one of the problems I was posed included checking if a key exists in an object.

The way I implemented this was by using the following:

if (myObj["keyName"]){  // or myObj.keyName
// do something
}
else{
// do something else
}

My solution was effective, but the interviewer taught me that another way I could check is by using myObj.hasOwnProperty(“keyName”).

I hadn’t encountered the hasOwnProperty() method before, and was eager to learn about it.

According to the MDN docs:

The hasOwnProperty() method returns a boolean indicating whether the object has the specified property as its own property (as opposed to inheriting it).

The benefit to using the hasOwnProperty() method is that if the key exists, but has a falsey value, (like 0, an empty string, false, etc) this will still evaluate to true, while with my implementation it will evaluate to false.

(For my code challenge, it didn’t make a difference, as my scenario would never have keys with falsey values, but I was still happy to learn about this method.)

After the interview, I started to look into the hasOwnProperty() method to try and learn a little more about it. During my research, I came across a third way to check if a key exists in an object, using the in operator.

if ("keyName" in myObj){
// do something
}

The MDN docs explain:

The in operator returns true if the specified property is in the specified object or its prototype chain.

The difference here is that unlike the hasOwnProperty() method, which will return false if the key is in the prototype chain but not the object’s own property, the inoperator will return true in this case.

For example, "keyname" in myObj is true for an inherited property like the constructor andtoString methods, but myObj.hasOwnProperty(“constructor”) returns false as it is an inherited property and not the myObj's own property.

To summarize, we’ve highlighted three different ways to check if an object has a specified property and the nuances in their behavior. We discussed myObj.keyname, myObj.hasOwnProperty("keyname"), and "keyname" in myObj. With this knowledge we are now better equipped to handle the various scenarios as they arise.

--

--