What is difference between "in" and "hasOwnProperty" in Javascript
Table of Contents
"in" in Javascript
The "in" operator returns true if the specified property is in the specified object and also in its prototype chain.
"hasOwnProperty" in Javascript
The "hasOwnProperty" method returns true if the specified property is in the specified object and not in its prototype chain.
Consider the following example:
const user = {
name: 'John',
age: 30
};
console.log('name' in user); // true
console.log(user.hasOwnProperty('name')); // true
both "in" and "hasOwnProperty" return true because the "name" property is in the "user" object.
now we check the "toString" property which is in the prototype chain of the "user" object.
const user = {
name: 'John',
age: 30
};
console.log('toString' in user); // true
console.log(user.hasOwnProperty('toString')); // false
As you can see, the "in" operator returns true because the "toString" property is in the prototype chain of the "user" object. However, the "hasOwnProperty" method returns false because the "toString" property is not in the "user" object.
Another example:
function Person() {
this.name = 'Nguyen Van A';
}
Person.prototype.age = 20;
const person = new Person();
console.log('name' in person); // true
console.log('age' in person); // true
console.log(person.hasOwnProperty('name')); // true
console.log(person.hasOwnProperty('age')); // false