3

I just read an article that suggests using the in operator for browser feature and object property detection. The example given is to use:

if("geolocation" in navigator) {
    // Do some stuff
}

rather than:

if(navigator.geolocation) {
    // Do some stuff
}

However, it made no mention of hasOwnProperty, despite the fact that the following code seems to work just fine:

if(navigator.hasOwnProperty('geolocation')) {
    // Do some stuff
}

Are there situations where I should use in instead of hasOwnProperty or vice-versa? Or is it simply a stylistic choice?

1
  • 2
    FWIW, typeof object.property !== undefined is a lot faster than in or hasOwnProperty: jsperf.com/hasownproperty-vs-in/2 (granted, it's not exactly equivalent, but that won't make a difference in most cases). Of course performance is only a concern if you have to do a lot of property checking (and feature detection is not one of those cases). Aug 3, 2013 at 22:50

1 Answer 1

5

There's a difference, from the MDN on hasOwnProperty:

Every object descended from Object inherits the hasOwnProperty method. This method can be used to determine whether an object has the specified property as a direct property of that object; unlike the in operator, this method does not check down the object's prototype chain.

My advice is, if you created the object then you can use in or a simple lookup most of the time, but consider your options when there's a prototype chain in place. If it's a native object or some other object you have no control of, then use hasOwnProperty.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.