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
Using the hasOwnProperty() method
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
Using the in operator
The in
operator checks if an object has a property with the specified name, including properties inherited from its prototype chain. It returns true
if the property exists, otherwise it returns false
.
const obj = { name: "John", age: 30 };
console.log("name" in obj); // Output: true
console.log("gender" in obj); // Output: false
Using the Object.keys() method
The Object.keys()
method returns an array of a given object’s own enumerable property names. You can then check if the property exists by searching for its name in the array.
const obj = { name: "John", age: 30 };
console.log(Object.keys(obj).includes("name")); // Output: true
console.log(Object.keys(obj).includes("gender")); // Output: false
Contact Us