How to check if object property exists with a variable holding the property name?
To determine if an object has a property with the name stored in a variable:
- Use
in
for checking the entire prototype chain:
- Use
hasOwnProperty()
to scan only the object itself, excluding the prototype chain:
Although hasOwnProperty()
gives a direct inspection, choosing in
brings advantages like flexibility with variable property names, and dodging the bullet if hasOwnProperty
gets overridden.
Dynamic property names handling
In the wacky world of dynamic property names, dot notation won't cut it. Instead, you want to use bracket notation which can put variables straight into the access syntax, turning properties into wild, spontaneous creatures:
Have a nested object? You can still check for the property hidden deep within:
Insights on property checks
While checking properties is mostly a breezy walk in the park, watch out for a few nasty potholes. For instance, hasOwnProperty()
might flop if it's overwritten by some prankster. Here's a workaround:
eval
function might lure you in for dynamic property checks, but resist! It's a security risk. Stay on the straight and narrow with bracket notation and in
.
Checking property existence and beyond
You can gear up typeof
and bracket notation to check not just existence but also verify data type:
And let's not forget the difference between something existing and it being truthy. Existence doesn't always equate truthiness:
Always quote property names when using hasOwnProperty
or the in
operator. Your future self (and your code) will thank you.
hasOwnProperty
vs in
- Battle of the titans
Your choice between hasOwnProperty
and in
should depend on what you're looking for:
hasOwnProperty
is your guy if you don't want to deal with prototype's properties.- Go for
in
if inheriting properties or variable property names are part of your game plan.
If hasOwnProperty()
has been overridden, check it on the prototype instead:
Keeping these distinctions in mind will save you from potential property-checking mishaps.
Was this article helpful?