How do I check if an object has a key in JavaScript?
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:
hasOwnProperty
example:
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.
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:
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:
Modern ECMAScript 2020 techniques
With ECMAScript 2020, Key checking is enjoying the spotlight thanks to optional chaining (?.
) and nullish coalescing (??
):
Was this article helpful?