- Full Stack Express
- Pages
- How to Check if a Key Exists in an Object
How to Check if a Key Exists in a JavaScript Object
When working with objects, we may need to check if a certain key exists or has a certain value.
Let’s say we have a dog object:
const dog = {
name: 'Jack',
color: 'white',
age: 5,
};
And we want to validate whether or not this dog object has the key age.
We can use the hasOwnProperty() method on the object, and see whether this returns true or false.
console.log(dog.hasOwnProperty(age)); // prints true
Another option we have is to use the in operator.
The in operator will return true if the key exists in our dog object.
The syntax is as follows: prop in object
In our example, our property or key is age, and our object is dog.
console.log('age' in dog); // prints true
A common practice is to always use a fallback to account for undefined values:
dog.age || 5
This will set a default value of 5 in the case that age doesn’t exist.