javascript

in vs hasOwnProperty in JavaScript


In this article, you are going to learn about the difference between hasOwnProperty and in.

In JavaScript, an object is a self-sustained entity, with properties and type. Compare it with a person, for example. A person is an object, with properties. A person has eyes, legs, weight, ears, hands, etc. In the same way, JavaScript objects have properties with their defined characteristics.

In JavaScript object, you can check whether it contains a key or not. To do so you can use two common methods. Those are in operator and hasOwnProperty() function. Lets see an example below:

const students = { 
        age: 22 
};
'age' in students; // true
students.hasOwnProperty('age'); // true

'name' in students; // false
students.hasOwnProperty('name'); // false

Both return true when the property age exists on the object and false for not existing property name in the object.

In the naked eye, you can not find any significant difference between them. Both give the same output in general. But don’t get confused with this. There’s a significant difference between them and that is for inherited properties in will return true on the other hand for inherited properties hasOwnproperty() will return false. see the example below:

const students = {
  age : 20
}

'constructor' in students; // true
'__proto__' in students; // true
'hasOwnProperty' in students; // true

students.hasOwnProperty('constructor'); // false
students.hasOwnProperty('__proto__'); // false
students.hasOwnProperty('hasOwnProperty'); // false

In JavaScript, the student Object base class has a proto, a constructor and a hasOwnProperty function. When we use an in operator it returns true as these are inherited properties and for the hasOwnProperty() function, it returns false because this function ignores inherited properties.

This is all about the hasOwnProperty() function and in operator in JavaScript Object.


Share on social media

//