Skip to content

How to check if a key exists in a JavaScript object

New Course Coming Soon:

Get Really Good at Git

Given a JavaScript object, you can check if a property key exists inside its properties using the in operator.

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')

When inheritance is an important part of your applications 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.

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.

Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. A course that helps you feel less frustrated with Git. Launching Summer 2024. Join the waiting list!
→ Get my JavaScript Beginner's Handbook
→ Read my JavaScript Tutorials on The Valley of Code
→ Read my TypeScript Tutorial on The Valley of Code

Here is how can I help you: