Using Object.hasOwn in Practice
You'll learn: Real-world patterns where Object.hasOwn() shines for safe property checks, object filtering, and robust existence tests.
Now that you understand why Object.hasOwn() is superior to hasOwnProperty(), let's see how to use it in everyday code scenarios.
Safe Property Checking
The most common pattern is checking if a property exists directly on an object (not inherited):
const user = { name: 'Alice', age: 30 };
if (Object.hasOwn(user, 'name')) {
console.log(user.name); // 'Alice'
}
if (Object.hasOwn(user, 'email')) {
console.log('Has email'); // Won't execute
}
Filtering Object Properties
When you need to iterate only over own properties:
const settings = { theme: 'dark', notifications: true };
const filtered = Object.keys(settings).filter(key =>
Object.hasOwn(settings, key) && settings[key] === true
);
console.log(filtered); // ['notifications']
Safely Handling User-Created Objects
This pattern prevents issues with objects that might have no prototype or shadowed properties:
const config = Object.create(null); // No prototype
config.apiKey = 'secret123';
// Safe, even with null prototype
if (Object.hasOwn(config, 'apiKey')) {
console.log('API key present');
}
// Would throw: config.hasOwnProperty is not a function
Distinguishing Own vs Inherited Properties
Useful when working with class instances:
const obj = { direct: 1 };
if (Object.hasOwn(obj, 'direct')) {
console.log('Own property');
}
if (Object.hasOwn(obj, 'toString')) {
console.log('Won't print'); // toString is inherited
}
Key Takeaway: Use Object.hasOwn(obj, prop) whenever you need to check for own properties—it's safer, clearer, and works reliably with null-prototype objects and potentially shadowed properties.