I have seen some posts dedicated to hasOwnProperty
but I still question whether (and when) it should be used over a simple obj.prop
if (obj.hasOwnProperty("prop"))
is useful for checking whether an object defines a non-inherited property prop
but is it all that much better than simply doing if (obj.prop)
?
The ladder is especially useful when you have nested objects. For example, if you have an object superheros
which has a property of dcComics
and within that property has another property of batman
To check whether batman is set using hasOwnProperty
you would have to:
if (superheros.hasOwnProperty("dcComics") && superheros.dcComics.hasOwnProperty("batman") {...}
Using simple prop check:
if (superheros.dcComics && superheros.dcComics.batman)
In most cases when you are not defining your own js objects, is it acceptable to just use obj.prop
?