For object property detection, should I use 'in' or 'hasOwnProperty'?

javascript

Solution

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`.

Problem

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?

Original source