Search code examples
javascripthasownproperty

Battle: hasOwnProperty vs obj.prop


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?


Solution

  • JimmyRare is correct. Your question assumes that the two methods are meant for getting the same result, which they are not. hasOwnProperty is used to make sure that an object itself has that property, and not one of its prototypal ancestors. Even if you're dealing with a 1-level object, they still don't do the same. A better similitude would be

    if (obj.hasOwnProperty('prop'))
    

    vs

    if (typeof obj.prop !== 'undefined')