In JavaScript, checking whether an object has a property of its own (and not inherited from its prototype chain) is a common task.
Traditionally, developers have used Object.prototype.hasOwnProperty.call(obj, key)
or the shorthand obj.hasOwnProperty(key)
. With ES2022, a new, more ergonomic method arrived: Object.hasOwn
.
In this article, weβll explore:
- Why
Object.hasOwn
exists - How it compares to legacy approaches
- Syntax and usage examples
- Polyfill for older environments
- Performance considerations
- Browser & environment support
- Best practices
π Background: The Legacy Approach
Before ES2022, to check if an object obj
has its own property prop
, you typically did:
if (obj.hasOwnProperty(prop)) {
// β¦
}
However, this can break if obj
shadows or deletes the inherited method:
const obj = {
hasOwnProperty: () => false,
foo: 42
};
obj.hasOwnProperty("foo"); // false β wrong!
To guard against that, the safest pattern was:
if (Object.prototype.hasOwnProperty.call(obj, "foo")) {
// obj truly has "foo" as its own property
}
But the syntax is verbose and repetitive. Enter Object.hasOwn
.
π Introducing Object.hasOwn
The ES2022 standard introduced a static method on Object
:
Object.hasOwn(obj, prop);
-
obj
: The target object -
prop
: The property key (string or symbol)
It returns true
if obj
has its own (non-inherited) property named prop
, and false
otherwise.
Example
const user = { name: "Alice" };
Object.hasOwn(user, "name"); // true
Object.hasOwn(user, "toString"); // false (inherited)
π Polyfill for Older Environments
If you need support in environments without Object.hasOwn
, you can add a small polyfill:
if (!Object.hasOwn) {
Object.hasOwn = function (obj, prop) {
return Object.prototype.hasOwnProperty.call(obj, prop);
};
}
Include this once at the top of your codebase (or in a setup file) to safely use Object.hasOwn
everywhere.
βοΈ Performance Considerations
Under the hood, Object.hasOwn(obj, prop)
calls the same algorithm as hasOwnProperty
. Benchmarks indicate negligible difference in performance. The main advantage is readability and safety against shadowed properties.
π Browser & Environment Support
Environment | Support |
---|---|
Chrome | 93+ |
Firefox | 92+ |
Safari | 15.4+ |
Node.js | 16.9+ |
For older runtimes, include the polyfill above.
π§° Best Practices
-
Prefer
Object.hasOwn
for clarity and safety. - Use descriptive variable names:
if (Object.hasOwn(cartItem, "quantity")) {
// handle quantity
}
-
Avoid
in
operator when you need to exclude inherited props:
"toString" in {} // true (inherited)
Object.hasOwn({}, "toString") // false
π Conclusion
Object.hasOwn
brings a concise, reliable way to check for own properties in objectsβguarding against prototype pitfalls and improving code readability. By adopting this modern method (and polyfilling where necessary), you can write cleaner, more maintainable JavaScript.
π Reference
Happy coding! π¨βπ»π©βπ»
Top comments (0)