This section demonstrates that hasOwn()
is immune to the problems that affect hasOwnProperty
. Firstly, it can be used with objects that have reimplemented hasOwnProperty()
:
const foo = {
hasOwnProperty() {
return false;
},
bar: "The dragons be out of office",
};
if (Object.hasOwn(foo, "bar")) {
console.log(foo.bar); // true - re-implementation of hasOwnProperty() does not affect Object
}
It can also be used with null
-prototype objects. These do not inherit from Object.prototype
, and so hasOwnProperty()
is inaccessible.
const foo = Object.create(null);
foo.prop = "exists";
if (Object.hasOwn(foo, "prop")) {
console.log(foo.prop); // true - works irrespective of how the object is created.
}