How to determine whether an object has a given property in JavaScript
To swiftly determine if an object has a specific property, use either the 'propertyName' in object
to include inherited properties, or object.hasOwnProperty('propertyName')
for just the object's own properties:
Lock 'n' Load with robust property checking
Being accurate in JavaScript is like art. Sometimes the star of the show isn't always on the stage:
Beware of the undefined creatures and null ghosts
Properties cloaked in undefined
or null
might exist, but they sure love to play hide-and-seek:
Own the property, or inherited real-estate?
hasOwnProperty
won't peek into the blueprint (sticking to the direct architecture). However, 'in
' doesn't care about lineage and scours the entire estate:
Existential Crisis: Is Undefined or Null?
Before asking for a map, ensure there isn't an abyss (undefined
or null
) in front of you. Trust me, runtime errors are no fun:
Dive deep with these treasure maps
Maps don't always work, especially when Captain JavaScript throws in diabolical puzzles for fun:
Modern Sea charts: Utility libraries
Trust me, Underscore.js or Lodash are no vintage maps. Methods like _.has(object, 'property')
navigate the sea of objects with a plunderer’s precision.
Reflect API: Advanced Navigation
Fear not! Modern JavaScript hasn’t forgotten you. Try Reflect.has(object, propertyKey)
. It’s similar to the in
operator but works with the powerful Reflect API.
"Ye Been Warned!" - Mysterious Corners of JavaScript
If you are one to defy the mighty JavaScript, here are few untold secrets:
Property Visibility Magic Show
Magic isn't real, but property enumerability can vanish a property in JavaScript:
Beware of the Deceivers
Global object properties like toString
can be spooky:
Alien Objects
Alien objects don't follow usual javascript prototype hierarchy. They can make hasOwnProperty
go haywire:
Was this article helpful?