Course contentsShow
← JavaScript
Lesson 628 of 2,72315. ObjectsFree lesson

hasOwnProperty() for Own Properties

Check if a property belongs directly to an object (not inherited) with hasOwnProperty().

hasOwnProperty() for Own Properties

You'll learn how to definitively check if a property belongs directly to an object, not its prototype chain.

What Problem Does This Solve?

You already know the in operator checks if a property exists anywhere in an object's prototype chain. But sometimes you need to know: "Does this specific object have this property, or did it inherit it from somewhere else?"

That's where hasOwnProperty() comes in.

How It Works

The hasOwnProperty() method returns true only if the property exists directly on the object itself, not inherited from its prototype:

const user = {
  name: 'Alice',
  age: 30
};

console.log(user.hasOwnProperty('name'));     // true
console.log(user.hasOwnProperty('age'));      // true
console.log(user.hasOwnProperty('toString')); // false (inherited)

Even though user.toString() works (inherited from Object.prototype), hasOwnProperty() correctly returns false because user doesn't own that property.

Comparing 'in' vs hasOwnProperty()

const person = { job: 'developer' };

console.log('job' in person);              // true
console.log(person.hasOwnProperty('job')); // true

console.log('toString' in person);              // true (inherited)
console.log(person.hasOwnProperty('toString')); // false (not owned)

The in operator finds both; hasOwnProperty() is more discriminating.

Real-World Use Case

This is especially useful when iterating over object properties and you want to skip inherited ones:

const product = { name: 'Laptop', price: 999 };

for (let key in product) {
  if (product.hasOwnProperty(key)) {
    console.log(key, product[key]); // Only own properties
  }
}

Key Takeaway: Use hasOwnProperty() when you need to distinguish between an object's own properties and those it inherited from its prototype chain.