Skip to content

How to check if a key exists in a JavaScript object

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.

β†’ Download my free JavaScript Handbook!

THE VALLEY OF CODE

THE WEB DEVELOPER's MANUAL

You might be interested in those things I do:

  • Learn to code in THE VALLEY OF CODE, your your web development manual
  • Find a ton of Web Development projects to learn modern tech stacks in practice in THE VALLEY OF CODE PRO
  • I wrote 16 books for beginner software developers, DOWNLOAD THEM NOW
  • Every year I organize a hands-on cohort course coding BOOTCAMP to teach you how to build a complex, modern Web Application in practice (next edition February-March-April-May 2024)
  • Learn how to start a solopreneur business on the Internet with SOLO LAB (next edition in 2024)
  • Find me on X

Related posts that talk about js: