The hasOwnProperty() method in JavaScript allows you to determine whether an object has a specific property. It is useful when you need to check if an object instance has a property with a particular name.
Syntax
The hasOwnProperty() method is called on an object instance and takes a string argument. It follows the syntax:
object.hasOwnProperty(property)
Return Value
If the object instance has a property with the name specified in the string argument, the method returns true
. On the other hand, if the object does not have the specified property, it returns false
.
Example
Consider the following example:
const person = { name: 'Fred', age: 87 };
person.hasOwnProperty('name'); // true
person.hasOwnProperty('job'); // false
In this example, the person
object has a property named 'name'
, so when we call person.hasOwnProperty('name')
, it returns true
. However, the object does not have a property named 'job'
, so person.hasOwnProperty('job')
returns false
.
Conclusion
The hasOwnProperty() method in JavaScript helps you determine whether an object instance has a specific property. By using this method, you can efficiently check if an object has a desired property and handle the results accordingly.
tags: JavaScript, hasOwnProperty, object properties