Object.hasOwn()
A static replacement for a method call that could always be broken by the object being tested. That is the whole reason it exists.
Demo
The third case is the point of the method: toString exists on every object via the prototype chain, and hasOwn reports FALSE because it is not an OWN property. The `in` operator would say true. The fourth case shows why this beats a truthiness check — the property exists but its value is null, so obj.a would be falsy while hasOwn correctly reports that the key is there. That distinction matters whenever null or 0 or empty string are legitimate values.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| object | object | yes | The object to inspect. null and undefined throw TypeError. |
| key | string | symbol | yes | The property key. Non-symbol values are coerced to strings, so 1 and "1" are the same key. |
Return value
boolean — True if the key is an OWN property of the object — inherited properties do not count. Works even when the object has a null prototype or a shadowed hasOwnProperty.
Common patterns
if (Object.hasOwn(config, "retries")) use(config.retries);
for (const k in data) { if (!Object.hasOwn(data, k)) continue; }
if ("toString" in obj) { }
Examples
Pitfalls
Object.create(null).hasOwnProperty("a")
Object.hasOwn(Object.create(null), "a")
const o = JSON.parse('{"hasOwnProperty": 1}'); o.hasOwnProperty("x")
Object.hasOwn(o, "x")
class A { m() {} } Object.hasOwn(new A(), "m")
"m" in new A()
Object.hasOwn(o, k)
Object.prototype.hasOwnProperty.call(o, k)
When to use
- Testing whether a key exists, including when its value is falsy
- Any object from untrusted input — parsed JSON, query strings
- Objects created with Object.create(null)
- Guarding a for...in loop
- You want inherited properties too → the in operator
- You only care whether the value is set → a truthiness or != null check
- You are listing every key → Object.keys
- Targeting runtimes older than 2021 → the borrowed-call form
Notes
FAQ
hasOwn for own properties, which is what data objects usually mean. in when inherited properties should count — checking for a method on a class instance, or feature-detecting on a DOM node.
Object.hasOwn(o, "toString"); // false "toString" in o; // true