When you have a JavaScript object, sometimes you want to check if a property/key exists on it or not.
In this post, we'll learn the best ways to check if a key exists in an object in JavaScript.
This is the example object we'll be using:
JAVASCRIPT
const object = {
name: "John",
age: 30
};
Using the in operator
The easiest way to check if a key exists is to use the in operator. The in operator will return a boolean value representing whether or not the key exists in the object.
That means you can use it in a conditional statement to check if a key exists in an object:
JAVASCRIPT
const object = {
name: "John",
age: 30
};
if ("name"in object) {
console.log("The name property exists in the object");
}
Using hasOwnProperty
Alternatively, you can use the hasOwnProperty method to check if a key exists in an object. The difference between the two is that in will check the prototype chain of the object to see if the key exists, whereas hasOwnProperty will only check the object itself.
Because there are subtle differences, they can return different results, so be aware that you're using the correct method to check if a key exists in an object.
This is how to use hasOwnProperty:
JAVASCRIPT
const object = {
name: "John",
age: 30
};
if (object.hasOwnProperty("name")) {
console.log("The name property exists in the object");
}
Fallback
In the case that your object does not have the key, you can use a fallback value.
The fallback value will be used if the key does not exist in the object, which is useful for when you don't want to use an empty string or null.