The Object.hasOwn()
method was introduced in ES2022 as a replacement for the more verbose
Object.prototype.hasOwnProperty.call()
. These methods return true
if the specified property of an object exists as its
own property. If the property is only available further down the prototype chain or does not exist at all - the methods return
false
.
If you are still using the old method - replace it with a simpler and more concise alternative.
You should also avoid calling the obj.hasOwnProperty()
method directly, without using Object.prototype
as a source. This
can lead to a runtime error if obj.prototype
is null
and therefore obj.hasOwnProperty
is undefined. The static
method Object.hasOwn()
does not depend on the obj.prototype
and is therefore safe to use in such cases.
Object.prototype.hasOwnProperty.call(obj, "propertyName"); // Noncompliant
Object.hasOwnProperty.call(obj, "propertyName"); // Noncompliant
({}).hasOwnProperty.call(obj, "propertyName"); // Noncompliant
To fix the code replace hasOwnProperty()
with Object.hasOwn()
Object.hasOwn(obj, "propertyName");