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
Object.prototype.hasOwnProperty
Instance method returning true if the object has the specified property as its own (non-inherited) property. Superseded by the safer static Object.hasOwn in ES2022.
Object.keys
Returns an array of a given object's own enumerable string-keyed property names. The order matches a normal for...in loop but excludes inherited and non-enumerable properties.
Object.getOwnPropertyDescriptor
Returns the property descriptor for an own property on the given object, or undefined if the property does not exist. Descriptors describe writability, enumerability, configurability, and getters/setters.
Object.values
Returns an array of a given object's own enumerable string-keyed property values. Introduced in ES2017 as a companion to Object.keys.
Object.entries
Returns an array of a given object's own enumerable string-keyed [key, value] pairs. Useful for iterating objects with for...of destructuring or converting to a Map.