JavaScript(JS) object method - hasOwnProperty
The hasOwnProperty()
method is a built-in method of the JavaScript Object
prototype. It returns a boolean indicating whether the specified object has the specified property as a direct property of that object.
Here's the syntax:
refer to:theitroad.comobj.hasOwnProperty(prop)
where obj
is the object to be inspected and prop
is the property to be checked. This method takes only one argument, which is the name of the property to be checked.
Here's an example that shows how to use the hasOwnProperty()
method:
const myObj = { prop1: "value1", prop2: "value2" }; console.log(myObj.hasOwnProperty("prop1")); // true console.log(myObj.hasOwnProperty("toString")); // false
In this example, we create an object myObj
with two properties prop1
and prop2
. We use the hasOwnProperty()
method to check whether the object has the prop1
and toString
properties. The prop1
property is a direct property of the object, so hasOwnProperty()
returns true
. The toString
property, on the other hand, is not a direct property of the object (it is inherited from the Object.prototype
), so hasOwnProperty()
returns false
.
The hasOwnProperty()
method is useful for checking whether a property exists in an object without looking in the prototype chain. Note that this method only checks for direct properties of the object, not inherited properties from the prototype chain. If you want to check for both direct and inherited properties, you can use the in
operator or the Object.keys()
method.