0

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?

Siguza
  • 21,155
  • 6
  • 52
  • 89
dipole_moment
  • 5,266
  • 4
  • 39
  • 55
  • 2
    What if `obj.prop === false`? The two methods would return very different answers -- reasonable, since they're testing different things. – Paul Roub Oct 06 '15 at 17:44
  • Good point. I have not mentioned in the question but i meant to say that i am interested in truthy checks. that is, no falsy, undefined, etc... – dipole_moment Oct 06 '15 at 17:49
  • [Iterating over objects](https://stackoverflow.com/a/684692). – Siguza Oct 06 '15 at 17:50

2 Answers2

1

obj.prop will follow prototype chain if the property is not on itself. obj.hasOwnProperty looks only for it's own properties.

JimmyRare
  • 3,958
  • 2
  • 20
  • 23
  • right but is there a good reason for using hasOwnProperty over obj.prop in situations when high performance is not an issue (you don't mind going up the prototype) chain and you know that prop is not defined higher up. For example, with ``dcComics`` it is safe to say it is not defined higher up. – dipole_moment Oct 06 '15 at 17:54
  • No. If you don't mind going up the prototype chain, you should never use hasOwnProperty. – Dan Crews Oct 06 '15 at 17:56
  • 1
    If you intend to travel up the prototype chain, don't use hasOwnProperty. If your intention is not to travel up the prototype chain, use hasOwnProperty. You should use the correct tool for the job, depending on the job itself. @dipole_moment –  Oct 06 '15 at 17:58
0

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')
Dan Crews
  • 3,067
  • 17
  • 20