How to use the hasOwnProperty() method In Javascript
The hasOwnProperty()
method checks if an object has a property with the specified name. It returns true
if the object has the property directly on itself (not inherited from its prototype chain), otherwise it returns false
.
const obj = { name: "John", age: 30 };
console.log(obj.hasOwnProperty("name")); // Output: true
console.log(obj.hasOwnProperty("gender")); // Output: false
How to check if an object has a specific property in JavaScript?
In JavaScript, you can check if an object has a specific property using various methods, such as the hasOwnProperty()
method, the in
operator, or using the Object.keys()
method.
Here’s how you can achieve it using these methods:
Table of Content
- Using the hasOwnProperty() method
- Using the in operator
- Using the Object.keys() method
Contact Us