DEV Community

Discussion on: JavaScript check if property exists in Object

Collapse
 
peerreynders profile image
peerreynders • Edited

Note that starting with ES2022 Object.prototype.hasOwnProperty() has been "replaced" with Object.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.

favicon developer.mozilla.org

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 external hasOwnProperty".

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.

Collapse
 
dailydevtips1 profile image
Chris Bongers

Oh nice addition Peer,
Missed that one on TC39, but great to see this adoption as it makes total sense.