
JavaScript hasOwnProperty
The JavaScript hasOwnProperty() method is used to determine whether an object has a specific property as its own property. It checks if the object contains the specified property and returns a boolean value indicating the result.
The syntax for using hasOwnProperty() is as follows:
object.hasOwnProperty(property)Here, object is the object on which you want to check for the property, and property is the name of the property you want to check.
Here’s an example that demonstrates the usage of hasOwnProperty():
var person = {
name: 'John',
age: 30
};
console.log(person.hasOwnProperty('name')); // true
console.log(person.hasOwnProperty('city')); // falseIn this example, we have an object called person with properties name and age. We use hasOwnProperty() to check if person has the properties 'name' and 'city'. The first console.log() statement returns true because person has the 'name' property as its own property. The second console.log() statement returns false because person does not have the 'city' property as its own property.
It’s important to note that hasOwnProperty() does not check for inherited properties. It only checks if the object has the specified property as its own property, not as a property inherited from its prototype chain.
Using hasOwnProperty() is particularly useful when iterating over object properties using a for...in loop (as mentioned in the previous response). It allows you to filter out inherited properties and focus only on the object’s own properties.