The hasOwnProperty() method checks if the specified property exists as an own property of the object, without looking in the prototype. Returns true if the property is found, and false if not or if it’s inherited.
const obj = { name: 'Alexander' };
console.log(obj.hasOwnProperty('name')); // true
console.log(obj.hasOwnProperty('toString')); // falseThe hasOwnProperty() method is a way to check if a property belongs to the object itself, not inherited from a prototype.
Checks only own properties of an object:
const obj = { name: 'John' };
console.log(obj.hasOwnProperty('name')); // true
console.log(obj.hasOwnProperty('toString')); // falseconst obj = {};
// All objects have toString, but it's inherited
console.log(obj.hasOwnProperty('toString')); // falseconst user = { name: 'John' };
if (user.hasOwnProperty('name')) {
console.log('Own property'); // Will trigger
}
if (user.hasOwnProperty('toString')) {
console.log('Own property'); // Won't trigger
}const parent = { inherited: 'value' };
const child = Object.create(parent);
child.own = 'value';
console.log(child.hasOwnProperty('own')); // true — own
console.log(child.hasOwnProperty('inherited')); // false — inheritedconst arr = [1, 2, 3];
// Array methods are inherited
console.log(arr.hasOwnProperty('push')); // false
console.log(arr.hasOwnProperty('length')); // true — own propertyconst obj = { name: 'John' };
// Safe iteration of only own properties
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
console.log(key, obj[key]); // Only own properties
}
}const obj = { name: 'John' };
// ❌ See all properties, including inherited
for (let key in obj) {
console.log(key); // name, toString, hasOwnProperty...
}
// ✅ Only own properties
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
console.log(key); // only name
}
}const data = { a: 1, b: 2 };
// Ensure properties are own, not inherited
Object.keys(data).forEach(key => {
if (data.hasOwnProperty(key)) {
console.log(key, data[key]);
}
});const obj = { name: 'John' };
// ❌ Sees everything, including inherited
console.log('toString' in obj); // true
// ✅ Sees only own properties
console.log(obj.hasOwnProperty('toString')); // falseconst obj = { name: 'John' };
// ❌ Error — not checking inheritance
for (let key in obj) {
console.log(obj[key]); // Will output name, toString, other methods
}
// ✅ Correct — checking inheritance
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
console.log(obj[key]); // Only name
}
}The hasOwnProperty() method is important for working with objects when you need to distinguish own properties from inherited ones.
Want more articles to prepare for interviews? Subscribe to EasyAdvice, bookmark the site and improve yourself every day 💪