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)) // evaluates to 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) // evaluates to true
A common practice is to always use a fallback to account for undefined values:
dog.age || 5 // evaluates to 5
This will set a default value of 5 in the case that age doesn’t exist.