Object.hasOwn vs hasOwnProperty in JavaScript
JavaScript’s ECMAScript 2022 (ES13) introduced
Object.hasOwn() as a modern replacement for the traditional
Object.prototype.hasOwnProperty() method. While both
methods determine whether an object contains a direct (non-inherited)
property, Object.hasOwn() solves long-standing edge cases
involving prototype inheritance, shadowed properties, and null-prototype
objects. This article explains why Object.hasOwn() was
introduced, the pitfalls of hasOwnProperty(), and how the
modern syntax simplifies your codebase.
The Limitations of
hasOwnProperty
The classic hasOwnProperty method exists on
Object.prototype. When invoked directly on an object
(object.hasOwnProperty('key')), it introduces two major
vulnerabilities:
Objects with No Prototype (
Object.create(null)): Objects created without a prototype do not inherit fromObject.prototype. CallinghasOwnPropertydirectly on them throws a runtimeTypeError.const nullProtoObj = Object.create(null); nullProtoObj.key = 'value'; // Throws TypeError: nullProtoObj.hasOwnProperty is not a function nullProtoObj.hasOwnProperty('key');Shadowed or Overwritten Properties: If an object defines its own property or method named
hasOwnProperty, the built-in prototype method is blocked or overridden.const user = { name: 'Alex', hasOwnProperty: false }; // Throws TypeError: user.hasOwnProperty is not a function user.hasOwnProperty('name');
The Legacy Workaround
To safely check properties before ES2022, developers had to borrow
the method directly from Object.prototype using
.call():
Object.prototype.hasOwnProperty.call(user, 'name'); // true
Object.prototype.hasOwnProperty.call(nullProtoObj, 'key'); // trueWhile functional, this approach is verbose, unintuitive, and prone to formatting errors.
How
Object.hasOwn() Fixes These Issues
Object.hasOwn() is a static method directly attached to
the global Object constructor rather than an instance
method on Object.prototype. It accepts two arguments: the
target object and the property key to check.
Object.hasOwn(object, propertyKey);Key Advantages of
Object.hasOwn()
Safe for Null-Prototype Objects: It evaluates objects created with
Object.create(null)without throwing errors.const nullProtoObj = Object.create(null); nullProtoObj.key = 'value'; Object.hasOwn(nullProtoObj, 'key'); // returns trueImmune to Shadowing: It ignores any property named
hasOwnPropertydefined on the target instance.const payload = { data: 'test', hasOwnProperty: 'invalid' }; Object.hasOwn(payload, 'data'); // returns trueCleaner and More Readable Syntax: It eliminates the need for
Object.prototype.hasOwnProperty.call(...).
Summary
Object.hasOwn() is the modern standard for checking
direct property existence in JavaScript. It provides a safer, more
concise, and robust alternative to
Object.prototype.hasOwnProperty(), effectively eliminating
legacy edge cases and verbose workarounds.