How to Check If A Key Exists In An Object In JavaScript

How to Check If A Key Exists In An Object In JavaScript

Ferenc Almasi β€’ Last updated 2021 September 18 β€’ Read time 3 min read
  • twitter
  • facebook
JavaScript

There are a couple of options you can play around with. Some more bulletproof than others. Let’s start with the most common ones. Imagine you have the following nested object and you want to retrieve the theme property:

Copied to clipboard! Playground
const user = { 
    settings: { 
        theme: 'default'  
    } 
}; 
object.js

Using the typeof operator:

The simplest way is to check if the value equals to undefined

Copied to clipboard!
if (typeof user.settings.theme !== 'undefined') { 
    // your property exists 
}
typeof.js

This presumes that settings is an existing object. If it’s not the case, you’ll get a TypeError.

Checking for truthiness:

You can also concatenate variables with the AND operator to create a boolean value.

Copied to clipboard!
if (user && user.settings && user.settings.theme) { 
    // your property exist 
} 
truthy.js

With this solution, you’ll get around the TypeError. However, you can see that if your object is deeply nested, checking each level, quickly makes the statement unreadable.

Using the in operator:

This will also return a boolean value:

Copied to clipboard!
if ('theme' in user.settings) { 
    // your property exist 
} 
in.js

The problem with this solution again is that it assumes that settings is an object. If it’s not, we get a TypeError.

Using the hasOwnProperty method:

Just like the in operator, this assumes the existence of settings, and can be only used reliably if we have a single level object.

Copied to clipboard!
if (user.settings.hasOwnProperty('theme')) { 
    // your property exist 
} 
hasOwnProperty.js

Using optional chaining:

Unlike the previous examples, this method provides a solution for unexisting parents.

Copied to clipboard!
if (user?.settings?.theme) { 
    // your property exist 
} 
optional-chaining.js

Even if settings is not an object, it won’t throw an error. However, there is a downside to this too. According to Caniuse, it’s only supported in ~78% of browsers at the writing of this solution. So you should not use it in a production environment. Make sure that you have a fallback option if you go with this option.

Bonus - Using the non-null assertion operator in TypeScript:

If you are using TypeScript, you can use the non-null assertion operator to check for the existence of properties. This works like optional chaining and will prevent TypeErrors.

Copied to clipboard!
if (user!.settings!.theme) { 
    // your property exist 
} 
non-null-assertion.js

What is the Difference Between the in and hasOwnProperty?

It’s important to know the difference between in and hasOwnProperty. If you need to check for inherited properties, you need to use the in operator. Otherwise you can go with hasOwnProperty as well. To emphasis the difference between the two, take a look at the following code example:

Copied to clipboard! Playground
// constructor is an inherited property
// therefore, this will return true
console.log('constructor' in window);

// this will however, return false
console.log(window.hasOwnProperty(constructor));
in-vs-hasOwnProperty.js

How to Work With Objects Error-Safe

Make sure to also check out, how you can get deeply nested properties error safe, and how to loop through an object, by clicking on one of the two tips below:

How to Safely Access Deeply Nested Properties in JavaScript
How to Safely Access Deeply Nested Properties in JavaScript
How to Loop Through Object Properties in JavaScript
How to Loop Through Object Properties in JavaScript

How to Check If A Key Exists In An Object In JavaScript
If you would like to see more Webtips, follow @flowforfrank
Looking to improve your skills? Check out our interactive course to master JavaScript from start to finish.
Master JavaScriptinfo Remove ads

Resources:

  • twitter
  • facebook
JavaScript
Did you find this page helpful?
πŸ“š More Webtips
Mentoring

Rocket Launch Your Career

Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies:

Courses

Recommended

This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.