Last month, my friend and mentor Chris Ferdinandi wrote about how to check if an object has a property in vanilla JS. I thought I’d follow up by explaining the difference between the
in operator and the
For the examples below, let’s consider a really simple constructor function:
The MDN Web Docs explain that the
true if the specified property is in the specified object or its prototype chain.
returns a boolean indicating whether the object has the specified property as its own property (as opposed to inheriting it).
What’s the difference?
In our simple example, we can see that the
in operator returns
true while the
hasOwnProperty() method returns
This is because the
in operator considers all properties—including inherited ones—while the
hasOwnProperty() method only considers the properties that exist directly on the object.
Person object we create has access to the
sayHello() method, but not directly. It is inherited from the
Person object’s prototype.
If you have questions, feedback, or any other suggestions, please do email me. I'd love to hear from you!