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:

  1. Objects with No Prototype (Object.create(null)): Objects created without a prototype do not inherit from Object.prototype. Calling hasOwnProperty directly on them throws a runtime TypeError.

    const nullProtoObj = Object.create(null);
    nullProtoObj.key = 'value';
    
    // Throws TypeError: nullProtoObj.hasOwnProperty is not a function
    nullProtoObj.hasOwnProperty('key');
  2. 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'); // true

While 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()

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.