DEV Community

Nadim Chowdhury
Nadim Chowdhury

Posted on

What is .hasOwnProperty() in JavaScript?

The hasOwnProperty method in JavaScript is a built-in method of the Object prototype. It checks whether the object has the specified property as its own property (as opposed to inheriting it).

Here's how hasOwnProperty works:

Enter fullscreen mode Exit fullscreen mode
  • object: The object you want to check.
  • property: The property name you want to check.


const obj = {
  name: 'John',
  age: 30

console.log(obj.hasOwnProperty('name'));  // true
console.log(obj.hasOwnProperty('age'));   // true
console.log(obj.hasOwnProperty('job'));   // false
Enter fullscreen mode Exit fullscreen mode

In this example:

  • obj.hasOwnProperty('name'): Returns true because obj has its own property named 'name'.
  • obj.hasOwnProperty('age'): Returns true because obj has its own property named 'age'.
  • obj.hasOwnProperty('job'): Returns false because obj does not have its own property named 'job'.

Why is it useful?

When dealing with objects in JavaScript, especially when iterating over their properties, it's common to use hasOwnProperty to check if a property belongs directly to the object or if it's inherited from the prototype chain.

For example, when using loop to iterate over an object's properties, hasOwnProperty can be used to filter out inherited properties:

for (let prop in obj) {
  if (obj.hasOwnProperty(prop)) {
    console.log(`Property ${prop} belongs directly to obj: ${obj[prop]}`);
Enter fullscreen mode Exit fullscreen mode

In this loop, hasOwnProperty ensures that only properties that belong directly to obj are processed, not properties inherited from its prototype chain. This can be particularly useful to avoid unexpected behavior when iterating over objects.

Disclaimer: This article was created with the help of AI.

Top comments (0)