DEV Community

Cover image for JavaScript check if property exists in Object
Chris Bongers
Chris Bongers

Posted on • Originally published at daily-dev-tips.com

JavaScript check if property exists in Object

You might need to determine if an object holds a particular property.

Let's say we have a user object. Optionally the email property can be set. If not, we want to show a form so the user can fill out their email.

How can we determine if this field exists?

const userOne = {
  name: 'Chris Bongers',
  email: 'info@daily-dev-tips.com',
};

const userTwo = {
  name: 'John Do',
};
Enter fullscreen mode Exit fullscreen mode

And to answer that, there are several ways of doing that. Let's take a look at the three most common ones.

Using hasOwnProperty to see if an object has a property

By using hasOwnProperty we can evaluate if an object has Own property.

Let's see how it would work on our example data.

console.log(userOne.hasOwnProperty('email'));
// Returns: true

console.log(userTwo.hasOwnProperty('email'));
// Returns: false
Enter fullscreen mode Exit fullscreen mode

That is perfect. But there is a catch to using this method. It only works for Own properties, not extended object properties.

As you may know, objects come with the toString method, and if we try to check if that exists, it will return false. (While this does exist)

console.log(userOne.toString());
// Returns: [object Object]

console.log(userOne.hasOwnProperty('toString'));
// Returns false
Enter fullscreen mode Exit fullscreen mode

Using in to see if an object has a property

Another more explicit way of checking if an object has a property is using in.

This one can check in own and inherited properties.

console.log('email' in userOne);
// Returns: true

console.log('email' in userTwo);
// Returns: false

console.log('toString' in userOne);
// Returns: true
Enter fullscreen mode Exit fullscreen mode

Using undefined to see if an object has a property

The last method is to use an undefined check. This method will work for omitted properties but can cause you headaches if the property exists but has an undefined value.

console.log(userOne.email !== undefined);
// Returns: true

console.log(userTwo.email !== undefined);
// Returns: false

console.log(userOne.toString !== undefined);
// Returns: true
Enter fullscreen mode Exit fullscreen mode

Now let's see what happens in the following example:

const userThree = {
  name: 'Steve Stevenson',
  email: undefined,
};

console.log(userThree.email !== undefined);
// Returns: false
Enter fullscreen mode Exit fullscreen mode

The check is acceptable, but it's not what we might be looking for.

Conclusion

When trying to find out if an object holds a particular property, we need to consider how safe we want to be.

I would generally not recommend using the undefined check.

If you only evaluate Own properties, the hasOwnProperty is a solid solution.

But you might want to be on the safe side and use the in check to determine if an object has a property.

Thank you for reading, and let's connect!

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter

Top comments (17)

Collapse
 
peerreynders profile image
peerreynders • Edited

Note that starting with ES2022 Object.prototype.hasOwnProperty() has been "replaced" with Object.hasOwn():

Object.hasOwn() - JavaScript | MDN

The Object.hasOwn() static method returns true if the specified object has the indicated property as its own property. If the property is inherited, or does not exist, the method returns false.

favicon developer.mozilla.org

Quote:

"JavaScript does not protect the property name hasOwnProperty; an object that has a property with this name may return incorrect results…

The recommended way to overcome this problem is to instead use Object.hasOwn() (in browsers that support it). Other alternatives include using an external hasOwnProperty".

For more details see: TC39 Proposal: Accessible Object.prototype.hasOwnProperty()

There even is an ESLint rule concerning this no-prototype-builtins.


To some degree this demonstrates that it is dangerous in JavaScript to think of objects as objects in the class-based object-oriented sense because there is no guarantee that every JavaScript object will have a prototype and therefore that Object will be in its prototype chain.

Collapse
 
dailydevtips1 profile image
Chris Bongers

Oh nice addition Peer,
Missed that one on TC39, but great to see this adoption as it makes total sense.

Collapse
 
supportic profile image
Supportic • Edited

You could also do if(userOne["email"]) but I would not recommend to check like this userOne.email !== undefined because what if the object in general does not exist?

if ({} !== undefined) true
=> true

if (undefined !== undefined) true
=> undefined
Enter fullscreen mode Exit fullscreen mode

means:
When userOne does not exist e.g. you forget to pass parameter in a function call, then (undefined).email !== undefined will evaluate not into false or true

undefined && true
=> undefined
undefined && false
=> undefined
Enter fullscreen mode Exit fullscreen mode

=> skip if condition

A fix for that though would be to check if the object exist and if not, assign an empty object to it.
options = options ?? {}
if (options.switch !== undefined) can now resolve in true or false.

Collapse
 
peerreynders profile image
peerreynders

what if the object in general does not exist?

As suggested in another comment optional chaining will work just fine here.

const options = undefined;
console.log(options?.email ? true : false); // false
// i.e. No Uncaught ReferenceError 
// even though options is `undefined`
Enter fullscreen mode Exit fullscreen mode
Collapse
 
dailydevtips1 profile image
Chris Bongers

Yeah that's why I mentioned the undefined check to be the least favorite one of all.
It get's messy and very prone to cause headaches later on.

Collapse
 
bacloud22 profile image
aben

I really like ensuring JavaScript safety by JavaScript built-in environment (browser, node..) and what the language has to offer itself. No typescript, no build systems...

I think it doesn't really make code complex not is it hard to achieve. With good discipline and attention I think the developer would have even more control on his code.

Thanks for the article

Collapse
 
dailydevtips1 profile image
Chris Bongers

Sometimes we tend to overcomplicate for no reason.
Plain JavaScript can handle a lot of things for us that actually might even work quicker.

Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited

You could also check for the existence of the property name in Object.keys(obj). Again, this only checks the objects own properties

Collapse
 
dailydevtips1 profile image
Chris Bongers

Ah yes, indeed another way of checking for own properties.

Collapse
 
iamhectorsosa profile image
Hector Sosa

Great article! I'll add into this using Optional chaining. It helps narrowing down your code when using TypeScript a ton. Of course, also very useful while writing plain JavaScript too.

Collapse
 
dailydevtips1 profile image
Chris Bongers

Optional changing can be a real life-saver when it comes to determining this indeed.

Collapse
 
moopet profile image
Ben Sinclair

You have a typo in your conclusion where you say

the safe side and use the on check to

but you mean "in".

Collapse
 
dailydevtips1 profile image
Chris Bongers

Thanks Ben!
Noticed and adjusted it 💖

Collapse
 
hnazmul profile image
H.Nazmul Hassan

Great man.. want more tips like this from you..

Collapse
 
dailydevtips1 profile image
Chris Bongers

Awesome!

Let's do some more hands-on tips 💪

Collapse
 
imiahazel profile image
Imia Hazel

Thanks for the snippets. These are perfect additions to my coding toolbox.

Collapse
 
dailydevtips1 profile image
Chris Bongers

Awesome Imia 💖