Problem Statement
What does hasOwnProperty() check?
Explanation
HasOwnProperty checks if a property exists directly on the object, not on its prototype chain.
It returns true only for own properties, not inherited ones.
This is useful when iterating over objects to avoid processing inherited properties.
Always use hasOwnProperty in for in loops to check own properties.
Modern alternative is Object hasOwn for better safety.
Code Solution
SolutionRead Only
const person = {
name: 'John',
age: 30
};
// Check own property
console.log(person.hasOwnProperty('name')); // true
console.log(person.hasOwnProperty('age')); // true
console.log(person.hasOwnProperty('city')); // false
// Inherited properties
console.log(person.hasOwnProperty('toString')); // false (inherited)
console.log('toString' in person); // true (checks prototype chain)
// Safe iteration with for...in
for (const key in person) {
if (person.hasOwnProperty(key)) {
console.log(key, person[key]);
}
}
// Modern alternative
const obj = {x: 1};
console.log(Object.hasOwn(obj, 'x')); // true (ES2022)
// Prototype example
function Animal() {}
Animal.prototype.species = 'animal';
const dog = new Animal();
dog.name = 'Buddy';
console.log(dog.hasOwnProperty('name')); // true (own)
console.log(dog.hasOwnProperty('species')); // false (inherited)
console.log(dog.species); // 'animal' (accessible but not own)