Skip to content
Tutorials Center
My learning

Topics

JavaScript Reference ยท Object

Object.prototype.hasOwnProperty()

Reference for JavaScript hasOwnProperty(): test whether an object has its own property, why Object.hasOwn() is preferred and the pitfalls of the old form.

hasOwnProperty() is a method inherited from Object.prototype. It returns true when the object has the given key as its own property, and false when the key is missing or only found further up the prototype chain.

It is the older way to ask "is this really stored on the object?". Modern code uses Object.hasOwn(), which does the same job without the pitfalls below.

JavaScript
obj.hasOwnProperty("name");
Object.hasOwn(obj, "name"); // preferred

Try it

JS Own versus inherited

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

No output.

JS Why Object.hasOwn() is safer

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

No output.

Syntax

JavaScript
obj.hasOwnProperty(prop)
Name Description
prop A string or symbol naming the property. Other values are converted to a property key first.

Return value: true if obj has an own property named prop (enumerable or not), otherwise false.

Exceptions: a TypeError if called on null or undefined, for example through .call(null, "x").

Usage notes

  • Includes non-enumerable properties. [].hasOwnProperty("length") is true, even though length does not show up in loops.
  • Ignores the prototype chain. Use the in operator when inherited members should count.
  • Can be shadowed. An object may define its own hasOwnProperty, as user-supplied JSON can, and then the call does something else.
  • Fails on null-prototype objects. Objects from Object.create(null) do not inherit the method, so calling it throws.
  • Safe legacy form: Object.prototype.hasOwnProperty.call(obj, key) avoids both problems, and it is what Object.hasOwn() replaced.
  • Array indexes are properties too: [10].hasOwnProperty(0) is true, and holes in sparse arrays give false.
  • Prefer Object.hasOwn() in new code. Keep hasOwnProperty() for code that must run in very old environments.

Browser support

hasOwnProperty() has worked in every browser for decades. The replacement Object.hasOwn() is newer, so check a compatibility table if you support old browsers.