MediumPrototypes & Inheritance🐛 Debug Challenge

hasOwnProperty vs in — different results for prototype method

Buggy Code — Can you spot the issue?

function Animal(name) {
  this.name = name;
}
Animal.prototype.speak = function() {
  return this.name + ' speaks';
};

const dog = new Animal('Rex');

// Both checks reference 'speak' — what do they log?
if (dog.hasOwnProperty('speak') === ('speak' in dog)) {
  console.log('same');
} else {
  console.log('different');
}
console.log(dog.hasOwnProperty('speak'));
console.log('speak' in dog);

Fixed Code

function Animal(name) {
  this.name = name;
}
Animal.prototype.speak = function() {
  return this.name + ' speaks';
};

const dog = new Animal('Rex');

if (dog.hasOwnProperty('speak') === ('speak' in dog)) {
  console.log('same');
} else {
  console.log('different');
}
console.log(dog.hasOwnProperty('speak'));
console.log('speak' in dog);

Bug Explained

Bug: The developer expects both checks to return the same result. hasOwnProperty only checks own properties; in checks the whole prototype chain.

Explanation: speak lives on the prototype — hasOwnProperty returns false. The in operator checks the entire chain — returns true.

Key Insight: hasOwnProperty = own properties only. in = entire prototype chain. Use hasOwnProperty to distinguish instance vs inherited properties.

More Prototypes & Inheritance Debug Challenges

MediumShared array on prototype mutates all instances

Practice spotting bugs live →

38 debug challenges with AI hints

🐛 Try Debug Lab