JavaScript

Check whether an object owns a property

Use Object.hasOwn to distinguish a property stored directly on an object from one inherited through its prototype. It also works when the object has no prototype.

Worked example

Node.js example · save as example.mjs and run node example.mjs

const parent = {theme: "dark"};
const settings = Object.create(parent);
settings.retries = 0;
console.log(Object.hasOwn(settings, "theme"));
console.log(Object.hasOwn(settings, "retries"));

How it works

A normal property read could retrieve theme from the parent object. HasOwn answers a narrower question about the record itself. This is useful when applying defaults or interpreting configuration fields where an inherited value should not count as a submitted field.

Limits and mistakes

Ownership is separate from validity. A directly stored property whose value is undefined still exists. HasOwn does not sanitize untrusted objects, prevent prototype pollution elsewhere, or establish that a field has the expected type.

Check the result

Expect false and true. Assign an own theme with value undefined and verify that ownership becomes true even though reading the field returns undefined.

Sources

Reference documentation for the behavior used in this guide: