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',
};
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
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
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
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
Now let's see what happens in the following example:
const userThree = {
name: 'Steve Stevenson',
email: undefined,
};
console.log(userThree.email !== undefined);
// Returns: false
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)
Note that starting with ES2022
Object.prototype.hasOwnProperty()
has been "replaced" withObject.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.
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 externalhasOwnProperty
".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.Oh nice addition Peer,
Missed that one on TC39, but great to see this adoption as it makes total sense.
You could also do
if(userOne["email"])
but I would not recommend to check like thisuserOne.email !== undefined
because what if the object in general does not exist?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=> 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.As suggested in another comment optional chaining will work just fine here.
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.
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
Sometimes we tend to overcomplicate for no reason.
Plain JavaScript can handle a lot of things for us that actually might even work quicker.
You could also check for the existence of the property name in
Object.keys(obj)
. Again, this only checks the objects own propertiesAh yes, indeed another way of checking for own properties.
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.
Optional changing can be a real life-saver when it comes to determining this indeed.
You have a typo in your conclusion where you say
but you mean "in".
Thanks Ben!
Noticed and adjusted it 💖
Great man.. want more tips like this from you..
Awesome!
Let's do some more hands-on tips 💪
Thanks for the snippets. These are perfect additions to my coding toolbox.
Awesome Imia 💖