Explain Codes LogoExplain Codes Logo

How do I check if an object has a key in JavaScript?

javascript
key-checks
object-properties
es2020
Anton ShumikhinbyAnton Shumikhin·Aug 18, 2024
TLDR

Wondering if an object has a specific key in JavaScript? You can use 'key' in object, which will dig through the object along with its prototypes, or object.hasOwnProperty('key') to focus strictly on the object.

'key' in object example:

if ('a' in {a: 1}) { console.log('Just like a treasure hunt, the key exists!'); }

hasOwnProperty example:

if ({a: 1}.hasOwnProperty('a')) { console.log('No need for a treasure map, the key exists!'); }

The in operator and prototype hierarchies

Yes! The in operator is quick and dirty, more suitable for hasty scenarios. But remember, it ventures down the prototype hierarchy, and you really don't want an unexpected result, do you?

Direct property checks: precious yet underestimated gems

.hasOwnProperty() is a direct check. It makes sure that the property resides in the object itself and not lost somewhere in the murky prototype chain.

if (Object.prototype.hasOwnProperty.call(myObj, 'myKey')) { console.log('The safe way to check for properties. No prototype shenanigans here!'); }

In JavaScript's kingdom, certain regulations like no-prototype-builtins ESLint rule exist. Merely reminding you those laws to avoid collisions while racing in the coding track.

The troublesome truthy, and risky comparisons

Alright, alright, let me tell you a little secret. Don't count on truthy checks (if (myObj['key'])). You don't want to slip on falsy values (0, false), do you?

Similarly, undefined or null as compatriots are unreliable bouncers for key presence.

Additional approaches: diving a bit deeper

Old friend Object.keys()

For instance, you can use our dear old Object.keys(obj), to get an array filled with the object's own property names, then check if your key is hanging out there:

if (Object.keys(myObj).includes('myKey')) { console.log('This old trick never disappoints for key checks!'); }

Object.entries() for the key-value pair

Object.entries() paired with Array.prototype.some() sends in a dynamic duo for key checking — valuable when you want to keep an eye on the value too:

if (Object.entries(myObj).some(([key, value]) => key === 'myKey')) { console.log('The value was feeling left out. Now it gets to join the party, too!'); }

Modern ECMAScript 2020 techniques

With ECMAScript 2020, Key checking is enjoying the spotlight thanks to optional chaining (?.) and nullish coalescing (??):

if (myObj?.myKey !== undefined) { console.log('Just casually revolutionizing key checks with ES2020!'); }