inspection

Object.hasOwn

Returns true if the specified object has the given property as its own property (not inherited). Added in ES2022 as the recommended replacement for Object.prototype.hasOwnProperty.

Object.hasOwn(obj, prop)

Parameters

Parameter Purpose
obj The target object
prop The property key (string or Symbol) to check
returns Boolean — true if the property exists as an own property

Examples

console.log(Object.hasOwn({ a: 1 }, 'a'));

Logs true

console.log(Object.hasOwn({ a: 1 }, 'toString'));

Logs false — 'toString' is inherited from Object.prototype

const bare = Object.create(null);
bare.x = 42;
console.log(Object.hasOwn(bare, 'x'));

Logs true — works on null-prototype objects (hasOwnProperty would throw)

console.log(Object.hasOwn([1, 2, 3], 1));

Logs true — index 1 exists on the array

Gotcha

Prefer Object.hasOwn over obj.hasOwnProperty() — it works on objects created with Object.create(null) and cannot be shadowed by a user-defined 'hasOwnProperty' key. Requires ES2022 (Node 16.9+ / all modern browsers).

Related methods

← All JS Object methods · Array methods · Spread vs rest