The Object.hasOwn() static method returns true if the specified object has the indicated property as its own property.
If the property is inherited, or does not exist, the method returns false.
"JavaScript does not protect the property name hasOwnProperty; an object that has a property with this name may return incorrect results…
The recommended way to overcome this problem is to instead use Object.hasOwn() (in browsers that support it). Other alternatives include using an external hasOwnProperty".
To some degree this demonstrates that it is dangerous in JavaScript to think of objects as objects in the class-based object-oriented sense because there is no guarantee that every JavaScript object will have a prototype and therefore that Object will be in its prototype chain.
Note that starting with ES2022
Object.prototype.hasOwnProperty()
has been "replaced" withObject.hasOwn()
:Object.hasOwn() - JavaScript | MDN
The Object.hasOwn() static method returns true if the specified object has the indicated property as its own property. If the property is inherited, or does not exist, the method returns false.
Quote:
"JavaScript does not protect the property name
hasOwnProperty
; an object that has a property with this name may return incorrect results…The recommended way to overcome this problem is to instead use
Object.hasOwn()
(in browsers that support it). Other alternatives include using an externalhasOwnProperty
".For more details see: TC39 Proposal: Accessible
Object.prototype.hasOwnProperty()
There even is an ESLint rule concerning this
no-prototype-builtins
.To some degree this demonstrates that it is dangerous in JavaScript to think of objects as objects in the class-based object-oriented sense because there is no guarantee that every JavaScript object will have a prototype and therefore that
Object
will be in its prototype chain.Oh nice addition Peer,
Missed that one on TC39, but great to see this adoption as it makes total sense.