Open In App

What is hasOwnProperty() method in JavaScript ?

In JavaScript, the hasOwnProperty() method is a built-in method of objects that is used to check if an object has a property with a specified name. It returns a boolean value indicating whether the object contains a property with the given name directly on itself (not inherited from its prototype chain).

Syntax:

object.hasOwnProperty(propertyName)

Example: Here, the hasOwnProperty() method is called on the obj object to check if it has properties named “name” and “gender”. Since “name” is an own property of obj, the method returns true. However, since “gender” is not an own property of obj, but a property that doesn’t exist in the object, the method returns false.




const obj = { name: "John", age: 30 };
 
console.log(obj.hasOwnProperty("name")); // Output: true
console.log(obj.hasOwnProperty("gender")); // Output: false

Output
true
false
Article Tags :