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)
object : The object on which to check for the presence of a property.
propertyName : The name of the property to check for.
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 .
Javascript
const obj = { name: "John" , age: 30 };
console.log(obj.hasOwnProperty( "name" ));
console.log(obj.hasOwnProperty( "gender" ));
|
|