hasOwnProperty vs in
Written byPhuoc Nguyen
Created
08 Jul, 2020
Last updated
17 Mar, 2021
Category
JavaScript
The
`in`
operator and `hasOwnProperty`
function are the common ways to check if an objects contains a particular key.js
const person = {
name: 'Foo',
};
'name' in person; // true
person.hasOwnProperty('name'); // true
#Differences
-
For inherited properties,
`in`
will return`true`
.`hasOwnProperty`
, as the name implies, will check if a property is owned by itself, and ignores the inherited properties.Let's reuse the person object from the previous example. Since it's a JavaScript object which has built-in properties such as`constructor`
,`__proto__`
, the following check return true:js'constructor' in person; // true'__proto__' in person; // true'toString' in person; // trueWhile`hasOwnProperty`
returns`false`
when checking against these properties and methods:jsperson.hasOwnProperty('constructor'); // falseperson.hasOwnProperty('__proto__'); // falseperson.hasOwnProperty('toString'); // false -
For the
`get`
and`set`
methods of a class,`hasOwnProperty`
also returns`false`
.For example, we have a simple class representing triangles:jsclass Triangle {get vertices() {return 3;}}// Create new instanceconst triangle = new Triangle();Despite the fact that`vertices`
is the property of`triangle`
:jstriangle.vertices; // 3'vertices' in triangle; // true`hasOwnProperty`
still ignores it:jstriangle.hasOwnProperty('vertices'); // false
#Good practice
In order to check the existence of a property, use
`hasOwnProperty`
. Use `in`
to check the existence of a method.#See also
Questions? 🙋
Do you have any questions about front-end development? If so, feel free to create a new issue on GitHub using the button below. I'm happy to help with any topic you'd like to learn more about, even beyond what's covered in this post.
While I have a long list of upcoming topics, I'm always eager to prioritize your questions and ideas for future content. Let's learn and grow together! Sharing knowledge is the best way to elevate ourselves 🥷.
Recent posts ⚡
Newsletter 🔔
If you're into front-end technologies and you want to see more of the content I'm creating, then you might want to consider subscribing to my newsletter.
By subscribing, you'll be the first to know about new articles, products, and exclusive promotions.
Don't worry, I won't spam you. And if you ever change your mind, you can unsubscribe at any time.
Phước Nguyễn