inspection
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.
obj.hasOwnProperty(prop) Parameters
| Parameter | Purpose |
|---|---|
| prop | The property key to check for on the object itself |
| returns | Boolean — true if it is an own property |
Examples
const o = { a: 1 };
console.log(o.hasOwnProperty('a')); Logs true
const o = { a: 1 };
console.log(o.hasOwnProperty('toString')); Logs false — inherited from Object.prototype
const evil = { hasOwnProperty: () => 'oops' };
console.log(evil.hasOwnProperty('anything')); Logs 'oops' — method can be shadowed, which is why Object.hasOwn is preferred
const bare = Object.create(null);
try { bare.hasOwnProperty('x'); } catch (e) { console.log(e.message); } Logs a TypeError message — null-prototype objects have no hasOwnProperty
Gotcha
Two footguns: it can be shadowed by an own property named 'hasOwnProperty', and it throws on Object.create(null). Always prefer Object.hasOwn(obj, key) in modern code.
Related methods
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.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.getOwnPropertyNames
Returns an array of all own string-keyed property names, including non-enumerable ones (but not Symbol keys). Useful for introspection where Object.keys is too restrictive.
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.