How to check if a key exists in a JavaScript object
By Flavio Copes
Learn how to check if a key exists in a JavaScript object using the in operator or hasOwnProperty(), and how they differ when properties are inherited.
Given a JavaScript object, you can check if a property key exists using the in operator or the hasOwnProperty() method. Which one you pick depends on whether you care about inherited properties.
Say you have a car object:
const car = {
color: 'blue'
}
We can check if the color property exists using this statement, that results to true:
'color' in car
We can use this in a conditional:
if ('color' in car) {
}
Another way is to use the hasOwnProperty() method of the object:
car.hasOwnProperty('color')
What’s the difference between the two?
When inheritance is an important part of your application structure, the difference is that in will result true even for properties inherited by parent objects. hasOwnProperty() doesn’t. It will only return true if the object has that property directly - not one of its ancestors.
Here it is in action:
const vehicle = { wheels: 4 }
const car = Object.create(vehicle)
car.color = 'blue'
'wheels' in car //true
car.hasOwnProperty('wheels') //false
car.hasOwnProperty('color') //true
There’s also a newer alternative, Object.hasOwn(). It behaves like hasOwnProperty(), but being a static method it also works on objects created with Object.create(null), which don’t inherit any methods:
Object.hasOwn(car, 'color') //true
Why not just check for undefined?
You might be tempted to write this:
if (car.color !== undefined) {
}
Be careful. This fails when the property exists but holds the value undefined:
const car = { color: undefined }
car.color !== undefined //false, but the key exists!
'color' in car //true
When the question is “does the key exist?”, use in or hasOwnProperty(). The undefined check answers a different question: “does the key have a value?”.
Falling back to a default value
I use a fallback mechanism when I want one property and fallback to a default value if that does not exist:
car.brand || 'Ford'
If the brand property key does not exist on the object, this statement results to the Ford string.
Watch out for falsy values, though. If brand holds 0, an empty string, or false, the || operator skips those too. Use ?? when you only want the fallback on null or undefined:
const car = { doors: 0 }
car.doors || 4 //4, wrong!
car.doors ?? 4 //0Related posts about js: