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 hasOwnProperty()
method.
For the examples below, let's consider a really simple constructor function:
/**
* Create a new Person object
* @param {String} name The person's name
*/
function Person (name) {
this.name = name;
}
/**
* Show a greeting in an alert dialog
*/
Person.prototype.sayHello = function () {
alert("Hello, my name is " + this.name + "!");
};
// Instantiate the constructor
var myFriend = new Person("Robert");
The in
operator
The MDN Web Docs explain that the in
operator returns
true
if the specified property is in the specified object or its prototype chain.
"sayHello" in myFriend; // true
The hasOwnProperty()
method
Meanwhile, the hasOwnProperty()
method returns a boolean indicating whether the object has the specified property as its own property (as opposed to inheriting it).
myFriend.hasOwnProperty("sayHello"); // false
What's the difference?
In our simple example, we can see that the in
operator returns true
while the hasOwnProperty()
method returns false
.
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.
Every new Person
object we create has access to the sayHello()
method, but not directly. It is inherited from the Person
object's prototype.
For more on this, check out Understanding Prototypes and Inheritance in JavaScript by Tania Rascia.