Course contentsShow
← JavaScript
Lesson 629 of 2,72315. ObjectsFree lesson

Object.hasOwn() (Modern Alternative)

Use Object.hasOwn() as a safer, more reliable replacement for hasOwnProperty().

Object.hasOwn() (Modern Alternative)

You'll learn a safer, more reliable way to check if an object has its own property using the modern Object.hasOwn() method.

Why Object.hasOwn() Exists

Remember hasOwnProperty()? It works great, but has a hidden weakness: it's a method borrowed from Object.prototype. If an object doesn't have Object.prototype in its prototype chain, or if someone overrides hasOwnProperty, things break.

Object.hasOwn() solves this by being a static method — it lives directly on the Object constructor, not on the prototype chain. This makes it bulletproof.

How It Works

The syntax is nearly identical, but you call it on Object instead of on the object you're testing:

const user = {
  name: 'Alice',
  age: 30
};

// Old way (still works, but less safe)
console.log(user.hasOwnProperty('name')); // true

// Modern way (recommended)
console.log(Object.hasOwn(user, 'name')); // true
console.log(Object.hasOwn(user, 'toString')); // false (inherited)

Why It's Safer

Objects created without normal prototypes can't use hasOwnProperty:

const noProto = Object.create(null);
noProto.city = 'Paris';

// This breaks! (noProto has no hasOwnProperty method)
// noProto.hasOwnProperty('city'); // Error

// This works perfectly
console.log(Object.hasOwn(noProto, 'city')); // true

Key Takeaway: Use Object.hasOwn(obj, prop) instead of obj.hasOwnProperty(prop) for safer, more reliable property checking that works even with unusual objects.