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:
'constructor' in person;
'__proto__' in person;
'toString' in person;
While hasOwnProperty
returns false
when checking against these properties and methods:
person.hasOwnProperty('constructor');
person.hasOwnProperty('__proto__');
person.hasOwnProperty('toString');
For the get
and set
methods of a class, hasOwnProperty
also returns false
.
For example, we have a simple class representing triangles:
class Triangle {
get vertices() {
return 3;
}
}
const triangle = new Triangle();
Despite the fact that vertices
is the property of triangle
:
triangle.vertices;
'vertices' in triangle;
hasOwnProperty
still ignores it:
triangle.hasOwnProperty('vertices');