Skip to content

Object.hasOwn(): safe own-property checks (ES2022)

  • What Object.hasOwn(obj, key) checks, compared with in and obj[key] !== undefined.
  • Why it replaces Object.prototype.hasOwnProperty.call(obj, key).
  • Its edge cases, and how to make lookups on user-supplied keys safe.
  • Why TypeScript does not narrow on it.

TL;DR: Object.hasOwn(obj, key) returns true when obj has an own property named key, whatever its value and whether or not it is enumerable. It is a static function, so it works on objects with no prototype and on objects that override hasOwnProperty.

It was added in ECMAScript 2022 and is supported by all current browsers and runtimes (details in Compatibility).

“Does this object have this key?” sounds like one question, but JavaScript code asks three different ones, and only one of them ignores both the value and the prototype chain. The example below uses a partial update from an invented OrdersPortal app, where notes: undefined means “clear the notes”.

Running the samples: save a sample as a .mjs file and run it with Node.js 22 (node sample.mjs), or paste it into a browser console. All outputs shown were produced with Node.js 22.23.

const patch = { notes: undefined, giftWrap: false };
// Three different questions:
console.log(patch.notes !== undefined); // has a defined value?
console.log('toString' in patch); // own OR inherited?
console.log(Object.hasOwn(patch, 'notes')); // own property, whatever its value?
console.log(Object.hasOwn(patch, 'toString'));
// Before ES2022: borrow the method from Object.prototype.
const has = Object.prototype.hasOwnProperty;
console.log(has.call(patch, 'notes'));
// Why borrowing was needed: the instance method can be missing or shadowed.
const dictionary = Object.create(null);
dictionary.refund = 'Money returned to the customer';
try {
dictionary.hasOwnProperty('refund');
} catch (error) {
console.log(error.constructor.name, '-', error.message);
}
const tricky = { hasOwnProperty: () => true };
console.log(tricky.hasOwnProperty('anything'), Object.hasOwn(tricky, 'anything'));
console.log(Object.hasOwn(dictionary, 'refund'));

Output:

false
true
true
false
true
TypeError - dictionary.hasOwnProperty is not a function
true false
true

obj.hasOwnProperty(key) is looked up on the object itself. A null-prototype dictionary has no such method, and any object, including one parsed from JSON, can define its own. The safe idiom was Object.prototype.hasOwnProperty.call(obj, key) (enforced by ESLint’s no-prototype-builtins); Object.hasOwn() is that idiom as a built-in.

// Fragment: signature
Object.hasOwn(obj, key); // boolean

The spec steps are ToObject(obj), ToPropertyKey(key), then HasOwnProperty, which asks the object for its own property descriptor and returns whether one exists. Consequences:

  • Any own property counts: enumerable or not, data or accessor, any value including undefined.
  • Keys are converted like any property key: numbers become strings, symbols stay symbols, objects go through toString().
  • Primitives are boxed, so Object.hasOwn('abc', 'length') is true. null and undefined throw a TypeError.
  • Proxies see a getOwnPropertyDescriptor trap call, not a has trap call.
const sku = Symbol('sku');
const item = { [sku]: 'A-77', 0: 'first' };
Object.defineProperty(item, 'hidden', { value: 1, enumerable: false });
console.log(Object.hasOwn(item, sku)); // symbols work
console.log(Object.hasOwn(item, 0)); // keys are converted with ToPropertyKey
console.log(Object.hasOwn(item, 'hidden')); // non-enumerable still counts
console.log(Object.hasOwn(['a', , 'c'], 1)); // array hole: no own property
console.log(Object.hasOwn('abc', 'length')); // primitives are boxed
console.log(Object.hasOwn(class { static x = 1; }, 'x'));
class Order { #id = 1; get id() { return this.#id; } }
console.log(Object.hasOwn(new Order(), 'id')); // the getter lives on Order.prototype
try {
Object.hasOwn(undefined, 'x');
} catch (error) {
console.log(error.constructor.name, '-', error.message);
}

Output:

true
true
true
false
true
true
false
TypeError - Cannot convert undefined or null to object

Private fields such as #id are not properties, so Object.hasOwn cannot see them; use the #id in obj brand check (ES2022) from the private fields page.

lib.es2022.object.d.ts declares hasOwn(o: object, v: PropertyKey): boolean. Passing a primitive is therefore a type error, and the plain boolean result means if (Object.hasOwn(obj, 'id')) does not narrow obj. The in operator does; for own-property semantics with narrowing, write a type guard:

// Fragment: type-checks with tsc --strict --target es2022 (TypeScript 6.0.3)
function hasOwnKey<T extends object, K extends PropertyKey>(obj: T, key: K): obj is T & Record<K, unknown> {
return Object.hasOwn(obj, key);
}
declare const body: object;
if (hasOwnKey(body, 'notes')) {
const notes: unknown = body.notes; // narrowed: body has an own 'notes'
}

OrdersPortal turns a carrier code from a query string into a label. A plain CARRIER_LABELS[code] lookup returns inherited values for constructor and __proto__, so a crafted URL renders a function’s source or [object Object]. Guarding with Object.hasOwn answers only for keys the table defines; the same guard keeps a for...in merge from copying inherited keys.

// OrdersPortal: look up a carrier's label by a code that comes from user input.
const CARRIER_LABELS = { ups: 'UPS Ground', fedex: 'FedEx Express', usps: 'USPS Priority' };
function carrierLabelUnsafe(code) {
return CARRIER_LABELS[code] ?? 'Unknown carrier';
}
function carrierLabel(code) {
return Object.hasOwn(CARRIER_LABELS, code) ? CARRIER_LABELS[code] : 'Unknown carrier';
}
for (const code of ['ups', 'dhl', 'constructor', '__proto__']) {
console.log(code.padEnd(12), '|', String(carrierLabelUnsafe(code)).slice(0, 30).padEnd(30), '|', carrierLabel(code));
}
// Merge a partial update without letting inherited keys leak in.
function applyPatch(order, patch) {
const next = { ...order };
for (const key in patch) {
if (!Object.hasOwn(patch, key)) continue; // skip inherited enumerable keys
next[key] = patch[key];
}
return next;
}
const base = Object.create({ status: 'refunded' }); // inherited, enumerable
base.notes = 'Ring the bell';
console.log(applyPatch({ id: 'o-1', status: 'paid' }, base));

Output:

ups | UPS Ground | UPS Ground
dhl | Unknown carrier | Unknown carrier
constructor | function Object() { [native co | Unknown carrier
__proto__ | [object Object] | Unknown carrier
{ id: 'o-1', status: 'paid', notes: 'Ring the bell' }

A Map or a null-prototype object (Object.create(null)) removes inherited keys entirely; Object.hasOwn is the guard when you cannot change the structure. New loops can use Object.keys() or Object.entries() and need no guard.

  • Using in when you mean “own”. 'constructor' in {} is true. Use in only when inherited properties should count, such as feature detection on prototypes.
  • Using obj[key] !== undefined as an existence test. It cannot tell a missing key from one set to undefined, and it reads inherited values. That distinction matters for PATCH semantics.
  • Expecting it to find class methods or getters on an instance. They live on the prototype, so Object.hasOwn(instance, 'method') is false.
  • Shipping it to old runtimes. Code for Safari before 15.4 or Node.js before 16.9 needs a polyfill or the call idiom.
  • Expecting TypeScript to narrow. Object.hasOwn() returns a plain boolean; see TypeScript.
Question Use
Does obj itself have key, whatever the value? Object.hasOwn(obj, key)
Is key available on obj or its prototypes? key in obj
Is the value present and not undefined? obj[key] !== undefined, or obj?.[key] ?? fallback
Is a private field present? #field in obj
Is the key in a Map? map.has(key)

Use Object.hasOwn() everywhere you used hasOwnProperty or its call form.

According to MDN’s browser compatibility data, Object.hasOwn() is supported in Chrome 93, Edge 93, Firefox 92, Safari 15.4 (including iOS), Node.js 16.9.0, Deno 1.13 and Bun 1.0. Internet Explorer never supported it. In TypeScript, the lib must include es2022. For older runtimes, core-js provides a polyfill, or fall back to Object.prototype.hasOwnProperty.call(obj, key).

1. Why was Object.hasOwn added when hasOwnProperty already existed? obj.hasOwnProperty(key) depends on the object: it throws for null-prototype objects and lies when the object defines its own hasOwnProperty. The robust call form was verbose and easy to forget; Object.hasOwn makes it a static function.

2. What is the difference between Object.hasOwn(obj, 'a'), 'a' in obj and obj.a !== undefined? hasOwn: own properties only, value ignored. in: own and inherited. The undefined comparison reads the value (inherited too) and reports false for a property set to undefined.

3. Senior scenario: a service looks up handlers with handlers[req.body.action](). A security review flags it. What is the risk and the fix? The key is attacker-controlled. Values like constructor, toString or __proto__ resolve to inherited members, so the code can call unintended functions or crash with a TypeError. Fix it by validating the action against an allow-list, guarding the lookup with Object.hasOwn(handlers, action) and checking that the value is a function, or by storing handlers in a Map or a null-prototype object. Return a 400 for unknown actions instead of throwing.

  • Object.hasOwn() (ES2022) is true for any own property, regardless of value or enumerability, and works on null-prototype objects.
  • in includes inherited properties; !== undefined conflates missing and undefined.
  • Guard lookups by untrusted keys with it, or use a Map. TypeScript does not narrow on it.