You can check if an object has a property in JavaScript using the hasOwnProperty()
method or the in operator.
-
hasOwnProperty()
method:This method returns a boolean value indicating whether the object has the specified property as its own property (not inherited from its prototype chain).
Here is an example:
const obj = { name: "John", age: 30 }; console.log(obj.hasOwnProperty("name")); // true console.log(obj.hasOwnProperty("gender")); // false
-
in
operator:This operator returns a boolean value indicating whether the specified property exists in the object, including properties inherited from its prototype chain.
Here is an example:
const obj = { name: "John", age: 30 }; console.log("name" in obj); // true console.log("gender" in obj); // false
Note that the
in
operator can also be used to check if an object has anindex
in an array or akey
in a map.
Thank you for reading, and let’s have conversation with each other
Thank you for reading my article. Let’s have conversation on Twitter and LinkedIn by connecting.