How can I check whether an object has its own property?
Quick answer
Use Object.hasOwn(object, key) to check whether a property belongs directly to that object. Use key in object when you want to include properties inherited through its prototype chain. Both checks can return true for an own property, but only in returns true for an inherited one. These checks test presence, not whether the property's value is useful or non-undefined. [S1] [S2]
The question, the details, the next step.
A practical checklist
Decide whether inherited properties should count for your task.
Use
Object.hasOwn(object, key)for direct ownership.Use
key in objectwhen the prototype chain should be included.Test one own property and one inherited property if the distinction matters.
Check the property's value separately if presence alone is not enough.
A few more useful answers
Does `in` return false when a property’s value is `undefined`?
No. in checks whether the property is present, and a present property with an undefined value still counts. [S2]
Can `Object.hasOwn()` return true for a property whose value is `null`?
Yes. It checks direct ownership, including when the property value is null or undefined. [S1]
Does `in` check only properties written directly on the object?
No. It checks the object and its prototype chain, so an inherited property can make the result true. [S2]
Sources
References used for this guide.
- [S1] Object.hasOwn() — JavaScript | MDN developer.mozilla.org · Checked
- [S2] in operator — JavaScript | MDN developer.mozilla.org · Checked
