The in operator checks if a property exists in an object or its prototype chain. The hasOwnProperty() method checks only own properties of an object, ignoring inherited ones. Main difference: in sees everything, hasOwnProperty sees only own properties.
In JavaScript there are two ways to check property existence: [in] operator and hasOwnProperty() method. They are similar, but have an important difference.
Checks property in object and its prototypes:
const obj = { name: 'John' };
console.log('name' in obj); // true
console.log('toString' in obj); // true (inherited)Checks only own properties of an object:
const obj = { name: 'John' };
console.log(obj.hasOwnProperty('name')); // true
console.log(obj.hasOwnProperty('toString')); // falseconst user = { name: 'John' };
// Check with in
if ('toString' in user) {
console.log('toString exists'); // Will trigger
}
// Check with hasOwnProperty
if (user.hasOwnProperty('toString')) {
console.log('toString exists'); // Won't trigger
}const obj = {};
// All objects have inherited methods
console.log('toString' in obj); // true
console.log(obj.hasOwnProperty('toString')); // falseconst parent = { inherited: 'value' };
const child = Object.create(parent);
child.own = 'value';
console.log('inherited' in child); // true (through prototype)
console.log(child.hasOwnProperty('inherited')); // false (not own)// ❌ Thinking toString is object property
const obj = {};
if (obj.hasOwnProperty('toString')) {
console.log('Has toString');
} else {
console.log('No toString'); // Will correctly trigger
}
// ✅ Proper check for general case
if ('toString' in obj) {
console.log('Can use toString'); // Will trigger
}// ❌ Missing inherited methods
const obj = { name: 'John' };
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
// Missed toString and other methods
}
}
// ✅ If all properties needed
for (let key in obj) {
if (key in obj) {
// Will work, but meaningless
// Better without check
}
}Understanding the difference between in and hasOwnProperty helps work with objects properly and avoid errors with inherited properties.
Want more articles to prepare for interviews? Subscribe to EasyAdvice, bookmark the site and improve yourself every day 💪