Hiprup

What is Object.hasOwn()?

Object.hasOwn(obj, key) is the modern, safe way to check whether an object has its own property.

  • Own only — ignores inherited properties (unlike the in operator).

  • Safer — works even when an object has no prototype or overrides hasOwnProperty.

Recommended replacement for obj.hasOwnProperty(key).

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

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

// Old way: hasOwnProperty
console.log(user.hasOwnProperty('name'));      // true

// Why hasOwn is safer:
const noProto = Object.create(null);
noProto.key = 'value';
// noProto.hasOwnProperty('key'); // TypeError! (no prototype)
Object.hasOwn(noProto, 'key');    // true (always works!)

Object.hasOwn checks own properties (not inherited). It is a static method — works on any object including those without a prototype.

The Object.create(null) example shows why: no prototype = no hasOwnProperty method, but Object.hasOwn still works.

Object.hasOwn replaces hasOwnProperty (safer for prototype-less objects). ES2022.

Know the edge case: Object.create(null) objects have no hasOwnProperty method.

What is Object.hasOwn()? | Hiprup