How to check if a certain property exists in an object?
There are three possible ways to check if a property exists in an object.
First , using the in
operator. The syntax for using the in
operator is like this propertyname in object
. It returns true
if the property exists otherwise it returns false
.
const o = {
"prop" : "bwahahah",
"prop2" : "hweasa"
};
console.log("prop" in o); //This logs true indicating the property "prop" is in "o" object
console.log("prop1" in o); //This logs false indicating the property "prop" is not in "o" object
Second, using the hasOwnProperty
method in objects. This method is available on all objects in JavaScript. It returns true
if the property exists otherwise it returns false
.
//Still using the o object in the first example.
console.log(o.hasOwnProperty("prop2")); // This logs true
console.log(o.hasOwnProperty("prop1")); // This logs false
Third, using the bracket notation obj["prop"]
. If the property exists it returns the value of that property otherwise this will return undefined
.
//Still using the o object in the first example.
console.log(o["prop"]); // This logs "bwahahah"
console.log(o["prop1"]); // This logs undefined