How to Fix "Do not access Object.prototype method 'hasOwnProperty' from target object" Error in JavaScript


How can we fix this “Do not access Object.prototype method ‘hasOwnProperty’ from target object” error in JavaScript?

As the error message says, this error comes up when using ESLint with Object.prototype methods.

ESLint’s no-prototype-builtins rule disallows calling some Object.prototype methods directly on object instances.

We’ll get an error like this:

Do not access Object.prototype method 'hasOwnProperty' from target object.

The workaround is to call the method from Object.prototype directly:

obj = { id: 1 }
Object.prototype.hasOwnProperty.call(obj, 'id');