Skip to content
Tutorials Center
My learning

Topics

JavaScript Reference ยท Object

Object.hasOwn()

Reference for JavaScript Object.hasOwn(): test whether an object has its own property, why it replaces hasOwnProperty() and how it differs from the in operator.

Object.hasOwn() tells you whether an object has a property as its own member, meaning that the property was set directly on that object and not inherited from its prototype chain. It returns true for own properties of any kind, including non-enumerable ones and those whose value is undefined.

It is the modern replacement for obj.hasOwnProperty(key). Because it is a static function, it also works on objects with a null prototype and on objects that define their own hasOwnProperty.

JavaScript
Object.hasOwn({ a: 1 }, "a");        // true
Object.hasOwn({ a: 1 }, "toString"); // false

Try it

JS Own versus inherited

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS Why not hasOwnProperty()

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Syntax

JavaScript
Object.hasOwn(obj, prop)
Name Description
obj The object to test. Primitives are converted to objects.
prop The property key (string, number or symbol) to look for.

Return value: true if obj has an own property named prop, otherwise false.

Exceptions: a TypeError if obj is null or undefined.

Usage notes

  • Own only. Inherited properties give false, while the in operator returns true for them. Choose in when inheritance matters.
  • Value does not matter. A property set to undefined or null still exists. Compare with obj.key !== undefined, which cannot tell "missing" from "set to undefined".
  • Non-enumerable properties count. Array length is an own property of every array.
  • Numbers become strings. Object.hasOwn([5], 0) finds the property "0". Strings have own index properties too.
  • Safer than hasOwnProperty(). It cannot be shadowed by data, and it does not fail on null-prototype objects. The older form is still found in legacy code.
  • Not for Map or Set. Use map.has(key) and set.has(value).
  • Getters are not called. It only checks for existence.

Browser support

Object.hasOwn() is a fairly recent addition that works in current browsers and runtimes. Older browsers do not have it, so check a compatibility table when you must support them.