Object.hasOwn(): safe own-property checks (ES2022)
What you’ll learn
Section titled “What you’ll learn”- What
Object.hasOwn(obj, key)checks, compared withinandobj[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.
Summary
Section titled “Summary”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).
The problem it solves
Section titled “The problem it solves”“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:
falsetruetruefalsetrueTypeError - dictionary.hasOwnProperty is not a functiontrue falsetrueobj.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.
How it works
Section titled “How it works”// Fragment: signatureObject.hasOwn(obj, key); // booleanThe 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')istrue.nullandundefinedthrow aTypeError. - Proxies see a
getOwnPropertyDescriptortrap call, not ahastrap 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 workconsole.log(Object.hasOwn(item, 0)); // keys are converted with ToPropertyKeyconsole.log(Object.hasOwn(item, 'hidden')); // non-enumerable still countsconsole.log(Object.hasOwn(['a', , 'c'], 1)); // array hole: no own propertyconsole.log(Object.hasOwn('abc', 'length')); // primitives are boxedconsole.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.prototypetry { Object.hasOwn(undefined, 'x');} catch (error) { console.log(error.constructor.name, '-', error.message);}Output:
truetruetruefalsetruetruefalseTypeError - Cannot convert undefined or null to objectPrivate 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.
TypeScript
Section titled “TypeScript”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'}Realistic example
Section titled “Realistic example”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, enumerablebase.notes = 'Ring the bell';console.log(applyPatch({ id: 'o-1', status: 'paid' }, base));Output:
ups | UPS Ground | UPS Grounddhl | Unknown carrier | Unknown carrierconstructor | 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.
Common mistakes
Section titled “Common mistakes”- Using
inwhen you mean “own”.'constructor' in {}istrue. Useinonly when inherited properties should count, such as feature detection on prototypes. - Using
obj[key] !== undefinedas an existence test. It cannot tell a missing key from one set toundefined, and it reads inherited values. That distinction matters forPATCHsemantics. - Expecting it to find class methods or getters on an instance. They live on the prototype, so
Object.hasOwn(instance, 'method')isfalse. - Shipping it to old runtimes. Code for Safari before 15.4 or Node.js before 16.9 needs a polyfill or the
callidiom. - Expecting TypeScript to narrow.
Object.hasOwn()returns a plainboolean; see TypeScript.
When to use it and when not to
Section titled “When to use it and when not to”| 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.
Compatibility
Section titled “Compatibility”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).
Interview questions
Section titled “Interview questions”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.
Key takeaways
Section titled “Key takeaways”Object.hasOwn()(ES2022) is true for any own property, regardless of value or enumerability, and works on null-prototype objects.inincludes inherited properties;!== undefinedconflates missing andundefined.- Guard lookups by untrusted keys with it, or use a
Map. TypeScript does not narrow on it.
Related pages
Section titled “Related pages”- Object.keys() and Object.entries(): iterate own keys without
for...inguards. - for…in: the loop that needs an own-property guard.
- Private class fields: the
#field in objbrand check. - Optional chaining and nullish coalescing: reading values that may be missing.
- JavaScript interview questions
Official references
Section titled “Official references”- ECMAScript Language Specification,
Object.hasOwn ( O, P )(current draft; first published in ECMAScript 2022) - ECMAScript Language Specification,
Object.prototype.hasOwnProperty ( V ) - TC39 proposal: Accessible
Object.prototype.hasOwnProperty - MDN: Object.hasOwn()
- ESLint:
no-prototype-builtinsandprefer-object-has-own - TypeScript 6.0.3:
lib.es2022.object.d.ts