Object.hasOwn: A Better hasOwnProperty
You'll learn why Object.hasOwn() is the modern, safer way to check if an object has its own property.
The Problem with hasOwnProperty
For years, we've used obj.hasOwnProperty(key) to check if a property belongs directly to an object (not inherited from its prototype). But this approach has a hidden danger: hasOwnProperty is a method on Object.prototype, which means it can be overridden or unavailable.
When hasOwnProperty Fails
// Case 1: Overridden method
const obj = {
hasOwnProperty: () => false,
name: "Alice"
};
console.log(obj.hasOwnProperty("name")); // false (wrong!)
// Case 2: Object with no prototype
const bare = Object.create(null);
bare.name = "Bob";
// bare.hasOwnProperty("name"); // TypeError!
The Object.hasOwn() Solution
Object.hasOwn(obj, key) is a static method that always works correctly:
const obj = {
hasOwnProperty: () => false,
name: "Alice"
};
console.log(Object.hasOwn(obj, "name")); // true (correct!)
const bare = Object.create(null);
bare.name = "Bob";
console.log(Object.hasOwn(bare, "name")); // true (works!)
Why It's Better
Think of Object.hasOwn() like calling customer service directly versus going through a middleman who might not relay your message. It bypasses any property shadowing or prototype issues and reliably tells you if a property exists on the object itself.
Key Takeaway: Always prefer Object.hasOwn(obj, key) over obj.hasOwnProperty(key) — it's more reliable, handles edge cases gracefully, and won't break if hasOwnProperty is overridden or missing.