if (key in object) or if(object.hasOwnProperty(key)

Do the following two statements produce the same output? Is there any reason to prefer one way to the other?

 if (key in object)

 if (object.hasOwnProperty(key))

Solution 1:

Be careful - they won't produce the same result.

in will also return true if key gets found somewhere in the prototype chain, whereas Object.hasOwnProperty (like the name already tells us), will only return true if key is available on that object directly (its "owns" the property).

Solution 2:

I'l try to explain with another example. Say we have the following object with two properties:

function TestObj(){
    this.name = 'Dragon';
}
TestObj.prototype.gender = 'male';

Let's create instance of TestObj:

var o = new TestObj();

Let's examine the object instance:

console.log(o.hasOwnProperty('name')); // true
console.log('name' in o); // true

console.log(o.hasOwnProperty('gender')); // false
console.log('gender' in o); // true

Conclusion:

  • in operator returns true always, if property is accessible by the object, directly or from the prototype

  • hasOwnProperty() returns true only if property exists on the instance, but not on its prototype

If we want to check that some property exist on the prototype, logically, we would say:

console.log(('name' in o) && !o.hasOwnProperty('name')); //false
console.log(('gender' in o) && !o.hasOwnProperty('gender')); //true - it's in prototype

Finally:

So, regarding to statement that these two conditions ...

if (key in object)
if (object.hasOwnProperty(key))

...produce the same result, the answer is obvious, it depends.