objectHasOwns
Prefer Object.hasOwn() over Object.prototype.hasOwnProperty.call() for checking own properties.
✅ This rule is included in the ts stylistic preset.
Object.hasOwn() is the modern, recommended way to check if an object has a property as its own property (not inherited from the prototype chain).
It provides a safer and more convenient alternative to older patterns like Object.prototype.hasOwnProperty.call() or calling hasOwnProperty() directly on objects.
Using Object.hasOwn() avoids potential issues with objects that don’t inherit from Object.prototype, such as objects created with Object.create(null) and objects that have overridden the hasOwnProperty method.
Examples
Section titled “Examples”const hasKey = obj.hasOwnProperty("key");if (obj.hasOwnProperty("prop")) { console.log("Has property");}const result = Object.prototype.hasOwnProperty.call(obj, "key");const exists = {}.hasOwnProperty.call(obj, "prop");const hasKey = Object.hasOwn(obj, "key");if (Object.hasOwn(obj, "prop")) { console.log("Has property");}const result = Object.hasOwn(obj, "key");const exists = Object.hasOwn(obj, "prop");Options
Section titled “Options”This rule is not configurable.
When Not To Use It
Section titled “When Not To Use It”If you need to support JavaScript environments that don’t have Object.hasOwn() (pre-ES2022), you might need to disable this rule or use a polyfill.
Object.hasOwn() is supported in Node.js 16.9.0+ and all modern browsers.
For projects with a large existing codebase using the older patterns, and projects where hasOwn and/or hasOwnProperty are overridden with custom semantics, this rule might not be applicable.
Further Reading
Section titled “Further Reading”- MDN: Object.hasOwn()
- MDN: Object.prototype.hasOwnProperty()
- TC39 Proposal: Accessible Object.prototype.hasOwnProperty
Equivalents in Other Linters
Section titled “Equivalents in Other Linters”- Biome:
noPrototypeBuiltins - ESLint:
prefer-object-has-own - Oxlint:
eslint/prefer-object-has-own