JavaScript's hasOwnProperty() Method

Hero image for JavaScript's hasOwnProperty() Method. Image by Anne Nygård.
Hero image for 'JavaScript's hasOwnProperty() Method.' Image by Anne Nygård.

In JavaScript, Object.prototype.hasOwnProperty() is a relatively simple method for object manipulation and introspection. Here I'd like to quickly explain hasOwnProperty(), its purpose, and offer a practical example to illustrate its use.


Understanding hasOwnProperty()

hasOwnProperty() is a method used to check whether an object has a property as its own (not inherited from its prototype chain).

Syntax

obj.hasOwnProperty(prop)
  • obj: The object that we want to test.
  • prop: The property name (string) to check for.

Why Use hasOwnProperty()

In JavaScript, objects can often inherit properties from their prototype. hasOwnProperty() helps in determining if a property is actually part of the object itself, rather than inherited, in which case you may want to process it differently.


An Example in Code

Consider an object person with its own properties:

const person = {  name: 'Lola',  age: 30,};console.log(person.hasOwnProperty('name'));  //=> trueconsole.log(person.hasOwnProperty('toString'));  //=> false
  • 'name' is the object's own property, so hasOwnProperty('name') returns true.
  • 'toString', however, is inherited from the object's prototype, so hasOwnProperty('toString') returns false.

Key Takeaways

Use hasOwnProperty() to check for an object's own properties. This can be essential for iterating over an object's properties, especially to distinguish between its own properties and those it has inherited from the prototype (or elsewhere).


Prefer Object.hasown() in New Code

hasOwnProperty() is still useful to understand, but in newer JavaScript I would usually reach for Object.hasOwn(object, property) first. It avoids calling a method from the object being checked, which is safer when the object has a strange prototype or a property named hasOwnProperty.

That is not just theoretical. Objects created with Object.create(null) do not inherit hasOwnProperty(), and usercontrolled data can sometimes shadow names you expected to be safe.


Wrapping Up

Object.prototype.hasOwnProperty() is a simple yet powerful method in JavaScript for object property checks. It ensures that you are working with properties that belong to the object itself, not properties inherited from its prototype, which is crucial for accurate data manipulation and validation in JavaScript applications.


Have a complex web platform issue?

Tell me what is blocked, what has changed, and what needs to be true after the fix. I'll come back with a practical next step.