JavaScript Object.hasOwnProperty()


The Object.hasOwnProperty() method checks if the object possesses the given property.

Example

const obj = {};
obj.id = 42;

// check if id is present in obj or not
console.log(obj.hasOwnProperty("id"));

// Output: true

hasOwnProperty() syntax

The syntax of the hasOwnProperty() method is:

obj.hasOwnProperty(prop)

Here, obj is the object in which we want to search for the property.

Being a static method, we need to access hasOwnProperty() using the class name Object.


hasOwnProperty() Parameters

The hasOwnProperty() method takes in:


hasOwnProperty() Return Value

The getPrototypeOf() method returns a Boolean value:

  • true - if the object possesses the specified property
  • false - if the object doesn't possess the specified property

Notes:

  • Unlike the in operator, this method does not check for a property in the object's prototype chain.
  • hasOwnProperty() returns true even if the value of the property is null or undefined.

Example : Javascript Object.hasOwnProperty()

// create an object with property id
const obj = {id: 42};

// check if id exists in obj 
console.log(obj.hasOwnProperty("id")); 

// Output: true

// check if name exists in obj 
console.log(obj.hasOwnProperty("name")); 

// Output: false

// inherited properties return false
console.log(obj.hasOwnProperty("toString")); 

// Output: false

In the above example, we have created an object obj with a single property id.

We then used the hasOwnProperty() method to check if obj has the id and name properties.

The output indicates that the object possesses id but doesn't possess the name property.

Finally, we used hasOwnProperty() to check if toString is defined in the object.

However, even though toString is a property of all objects in JavaScript, we still get false as an output.

This is because toString is an inherited property rather than a property that has been directly defined in the object itself.


Also Read:

Did you find this article helpful?