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.
obj.hasOwnProperty("name"); Object.hasOwn(obj, "name"); // preferred
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
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")istrue, even thoughlengthdoes not show up in loops. - Ignores the prototype chain. Use the
inoperator 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 whatObject.hasOwn()replaced. - Array indexes are properties too:
[10].hasOwnProperty(0)istrue, and holes in sparse arrays givefalse. - Prefer
Object.hasOwn()in new code. KeephasOwnProperty()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.