Explain Codes LogoExplain Codes Logo

Checking if a key exists in a JavaScript object?

javascript
key-checks
hasownproperty
object
Nikita BarsukovbyNikita Barsukov·Aug 10, 2024
TLDR

To verify if a key is present in a JavaScript object:

The in operator checks not only the object itself, but also its prototype chain:

'key' in obj // true if 'key' exists - don't forget the string enclosure 😎

The .hasOwnProperty() method looks for a key exclusively within the object, excluding the prototype chain:

obj.hasOwnProperty('key') // true if 'key' is an "own" property - kinda selfish though

The method you choose heavily relies on whether you want to inspect the inherited properties or not.

Detailing key checks

Key checking with JavaScript objects can trick you into undefined weirdness or prototype chain mysteries. But don't worry, we've got you covered!

The in operator: More than meets the eye

The in operator heroically checks for both own and inherited properties:

if ('toString' in {}) console.log('Exists! As part of inheritance though'); // turns out you could 'toString' everything

But beware! If you want to ignore the inherited properties, choose hasOwnProperty.

Direct access vs. hasOwnProperty

You're in a hurry? Direct property access might be your fastest route:

if (obj.key !== undefined) console.log('Key is here!'); // isn't 'undefined' the irony of JS?

However, this cannot distinguish between a missing key and a key holding the value undefined. To avoid such a chaotic scenario, hasOwnProperty is the knight in shining armor.

The undefined dizziness

If you're trying to differentiate between an absent key and undefined value, it's safer to use the strict equality check (===) :

if (obj.key === undefined) console.log('Key is absent or maybe..it\'s just undefined'); // Schrödinger’s cat again?

The fledgling Object.hasOwn()

A new player has entered the game: Object.hasOwn(). It functions akin to hasOwnProperty:

if (Object.hasOwn(obj, 'key')) console.log('Key exists! And it\'s "own" property. Indeed.'); // keys can be possessive

Ensure to check the browser support if you're planning to use this in front-end code, unless you're fond of "undefined is not a function" screen-real-estate.

Property descriptors and immutability

For those seeking perfection through immutability or granular control over key characteristics, peek into Object.defineProperty() and Object.getOwnPropertyDescriptor().

Negating existence - the right way

In case you need to negate key existence, a pair of parentheses is your sponsor:

if (!('key' in obj)) console.log('Key is missing'); // you got ghosted by a key, really?

It is quintessential to ensure the ! operator intends for in expression, not just the key.

The null vs. undefined conundrum

Differentiating intentional absence of a value (null) from non-existent value (undefined) is paramount. null could be your rescue for explicitly empty properties:

obj.mightBeMissing = null; if (obj.mightBeMissing === null) console.log('Key exists but has no value'); // the key's on vacation!

Every key is sacred

Before you dare to access the value of a key, make sure it exists! This wisdom is your passport to avoid runtime errors:

if ('key' in obj) { // Key exists; you may pass! process(obj.key); // feel like a VIP yet? }