DEV Community

Cover image for JavaScript check if property exists in Object

JavaScript check if property exists in Object

Chris Bongers on July 05, 2022

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. I...
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 πŸ’–