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).


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.


Categories:

  1. Adaptive Development
  2. Cross‑Browser Compatibility
  3. Development
  4. Front‑End Development
  5. Guides
  6. JavaScript
  7. Responsive Development