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

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