search ]

Understanding the JavaScript hasOwnProperty() Method

The hasOwnProperty() method in JavaScript is vital for differentiating between properties owned by an object and those inherited through its prototype chain. This method checks if a specified property is a direct property of the object, rather than inherited, and returns a boolean value.

If you want to understand the basics first, check out our post on JavaScript Objects for Beginners.

How hasOwnProperty() Works

hasOwnProperty() is called on an object, passing the name of the property you want to check as a string. It returns true if the property is an own property of the object and false otherwise. This method does not check the prototype chain.

Simple Example 1: Checking Object Properties

const car = {
  make: 'Toyota',
  model: 'Corolla'
};

console.log(car.hasOwnProperty('make'));  // Output: true
console.log(car.hasOwnProperty('year'));  // Output: false

This example shows how to use hasOwnProperty() to check whether specific properties are directly defined on an object, distinguishing between existing own properties and those that do not exist.

Simple Example 2: Using hasOwnProperty in a Function

function hasProperty(obj, prop) {
  return obj.hasOwnProperty(prop);
}

const bike = {
  brand: 'Trek',
  type: 'mountain'
};

console.log(hasProperty(bike, 'brand'));  // Output: true
console.log(hasProperty(bike, 'price'));  // Output: false

This example demonstrates how to encapsulate hasOwnProperty() within a function to create a reusable utility for verifying object properties.

Complex Example: Filtering Inherited Properties

This example demonstrates filtering an object’s own properties from those inherited from its prototype.

function Vehicle(type) {
  this.type = type;
}

Vehicle.prototype.start = function() {
  return 'Starting...';
};

const car = new Vehicle('Car');
car.make = 'Toyota';
car.model = 'Corolla';

for (let prop in car) {
  if (car.hasOwnProperty(prop)) {
    console.log('Own property:', prop);
  } else {
    console.log('Inherited property:', prop);
  }
}
// Output: Own property: type
// Output: Own property: make
// Output: Own property: model
// Output: Inherited property: start

The for...in loop iterates over all enumerable properties, including inherited ones. Using hasOwnProperty() inside the loop lets you filter out prototype properties and process only the object’s own properties.

The Modern Alternative: Object.hasOwn()

ES2022 introduced Object.hasOwn() as a modern replacement for hasOwnProperty(). It works the same way but solves two edge cases where hasOwnProperty() can fail.

Why Object.hasOwn() Is Recommended

hasOwnProperty() can break in two situations:

  • Objects created with Object.create(null) don’t have a prototype, so hasOwnProperty() doesn’t exist on them.
  • If an object overrides hasOwnProperty with its own property, calling it directly will use the overridden version instead of the original.
// Object.create(null) - no prototype chain
const config = Object.create(null);
config.debug = true;

// This throws an error:
// config.hasOwnProperty('debug'); // TypeError

// Object.hasOwn() works correctly:
console.log(Object.hasOwn(config, 'debug')); // true
// Overridden hasOwnProperty
const obj = {
  hasOwnProperty: () => false, // overridden!
  name: 'test'
};

console.log(obj.hasOwnProperty('name'));    // false (incorrect!)
console.log(Object.hasOwn(obj, 'name'));    // true  (correct)

Object.hasOwn() is supported in all modern browsers since 2022. For new code, prefer Object.hasOwn() over hasOwnProperty(). If you need to support older environments, the Object.prototype.hasOwnProperty.call(obj, prop) pattern is the safest fallback.

Refactored Examples with Object.hasOwn()

Here are the earlier examples rewritten with the modern syntax:

const car = {
  make: 'Toyota',
  model: 'Corolla'
};

console.log(Object.hasOwn(car, 'make'));  // true
console.log(Object.hasOwn(car, 'year'));  // false

And filtering inherited properties in a for...in loop:

for (let prop in car) {
  if (Object.hasOwn(car, prop)) {
    console.log('Own property:', prop);
  } else {
    console.log('Inherited property:', prop);
  }
}

Live Example

This interactive example demonstrates how hasOwnProperty() works. Enter a property name in the input field and click the button to check whether it exists directly on the sample object.

The function retrieves the property name from the input, checks if it exists as an own property of sampleObject using hasOwnProperty(), and displays the result.

HTML:

<input type="text" id="propertyName" placeholder="Enter property name">
<button onclick="checkProperty()">Check Property</button>
<p id="result"></p>

JavaScript:

const sampleObject = {
    name: 'Sample',
    value: 100
};

function checkProperty() {
    const propName = document.getElementById('propertyName').value;
    const hasProp = Object.hasOwn(sampleObject, propName);
    document.getElementById('result').textContent = hasProp ?
        `${propName} is an own property.` :
        `${propName} is not an own property.`;
}

Result:

In this example, entering “name” or “value” will return true because these properties are defined directly on the sampleObject. Any other property name will return false.

FAQs

What is the difference between hasOwnProperty() and the in operator?
hasOwnProperty() checks only the object's own properties. The in operator checks both own properties and inherited ones from the prototype chain. For example, 'toString' in obj returns true (inherited from Object.prototype), while obj.hasOwnProperty('toString') returns false.
Should I use Object.hasOwn() or hasOwnProperty()?
For new code, use Object.hasOwn(). It handles edge cases that hasOwnProperty() cannot, such as objects created with Object.create(null) or objects that override hasOwnProperty. It's supported in all modern browsers since 2022 and is recommended by ESLint's prefer-object-has-own rule.
Does hasOwnProperty() work with arrays?
Yes. Arrays in JavaScript are objects, so hasOwnProperty() works on them. Array indices are stored as string keys, so [10, 20, 30].hasOwnProperty('0') returns true. The length property also returns true since it's an own property of every array. Methods like push and map return false because they are inherited from Array.prototype.
Why does hasOwnProperty() fail on Object.create(null)?
Object.create(null) creates an object with no prototype at all - it doesn't inherit from Object.prototype. Since hasOwnProperty() is defined on Object.prototype, calling it on such an object throws a TypeError. The workaround is to use Object.prototype.hasOwnProperty.call(obj, prop), or simply use the modern Object.hasOwn(obj, prop).
Is hasOwnProperty() deprecated?
No, hasOwnProperty() is not deprecated and still works in all browsers. However, Object.hasOwn() (ES2022) is the recommended modern alternative because it's safer and more concise. The ESLint rule prefer-object-has-own encourages migrating to Object.hasOwn() in codebases that support ES2022 or later.

Conclusion

The hasOwnProperty() method is a fundamental tool for managing object properties in JavaScript, helping you distinguish between an object’s own properties and those inherited from the prototype chain. For new code, prefer Object.hasOwn() as a safer and more concise alternative.

Understanding how property ownership works will help you write more reliable code, especially when iterating over objects with for...in or working with dynamic data. To learn about a closely related data structure, explore our guide to JavaScript arrays.

Comments are closed
Savvy WordPress Development official logo