Problem Statement
What is the difference between hasOwnProperty and the in operator?
Explanation
HasOwnProperty checks if a property exists directly on the object, not in its prototype chain.
The in operator checks if a property exists anywhere in the prototype chain, including inherited properties.
Use hasOwnProperty when you only want own properties, not inherited ones.
This is important when iterating over objects to avoid processing inherited properties.
Modern alternative is Object.hasOwn for better safety.
Understanding this difference is crucial for working with prototypes.
Code Solution
SolutionRead Only
function Person(name) {
this.name = name;
}
Person.prototype.greet = function() {
console.log('Hello');
};
const john = new Person('John');
john.age = 30;
// hasOwnProperty - only own properties
console.log(john.hasOwnProperty('name')); // true (own)
console.log(john.hasOwnProperty('age')); // true (own)
console.log(john.hasOwnProperty('greet')); // false (inherited)
// in operator - checks prototype chain
console.log('name' in john); // true (own)
console.log('age' in john); // true (own)
console.log('greet' in john); // true (inherited)
console.log('toString' in john); // true (from Object.prototype)
// Iterating safely with for...in
for (let key in john) {
console.log(key); // name, age, greet (includes prototype)
}
for (let key in john) {
if (john.hasOwnProperty(key)) {
console.log(key); // name, age (only own)
}
}
// Modern alternative - Object.keys (only own enumerable)
const ownKeys = Object.keys(john);
console.log(ownKeys); // ['name', 'age']
// Object.hasOwn (ES2022) - safer than hasOwnProperty
console.log(Object.hasOwn(john, 'name')); // true
console.log(Object.hasOwn(john, 'greet')); // false
// Why Object.hasOwn is better
const obj = Object.create(null); // No prototype
// obj.hasOwnProperty('x'); // TypeError!
Object.hasOwn(obj, 'x'); // false (safe)
// Practical example - checking property
function getValue(obj, key) {
if (obj.hasOwnProperty(key)) {
return obj[key];
}
return 'Property not found';
}