hasOwnProperty Problems and Shadowing
You'll learn why the traditional hasOwnProperty method can fail or behave unexpectedly, and why modern code avoids it.
The Core Problem
For years, developers used obj.hasOwnProperty('prop') to check if an object owns a property directly (not inherited). But there's a serious flaw: hasOwnProperty is just a method inherited from Object.prototype, which means it can be shadowed (overridden) or even missing entirely.
When hasOwnProperty Gets Shadowed
If an object defines its own hasOwnProperty property, it masks the inherited method:
const user = {
name: 'Alice',
hasOwnProperty: 'I am not a function!'
};
// This will crash:
// user.hasOwnProperty('name'); // TypeError: user.hasOwnProperty is not a function
The shadowing breaks the check completely. It's like asking someone "Do you own a car?" but they've replaced their ability to answer with a sign that just says "Maybe!"
When hasOwnProperty Is Missing
Objects created without Object.prototype (via Object.create(null)) have no inherited methods at all:
const config = Object.create(null);
config.apiKey = 'secret';
// This will also crash:
// config.hasOwnProperty('apiKey'); // TypeError: config.hasOwnProperty is not a function
The Traditional Workaround
Before ES2022, developers used this workaround:
const hasOwn = Object.prototype.hasOwnProperty.call(config, 'apiKey');
console.log(hasOwn); // true
This directly calls the original method from Object.prototype, bypassing any shadowing or missing methods.
Key Takeaway: obj.hasOwnProperty() is unreliable because it can be shadowed or missing; always use Object.hasOwn() (modern) or the call pattern (legacy) for safety.