Learn how to prevent the "do-not-access-objectprototype-method" error from appearing when building your JavaScript application.

How to fix ESLint error: Do not access Object.prototype method 'hasOwnProperty' from target object  no-prototype-builtins

Starting a new project with Vue.js will automatically generate a boilerplate that is configured to work with ESLint.  ESLint is a pluggable and configurable linter tool that helps you to identify and report bad patterns in JavaScript, so you can maintain your code quality with ease. If you start programming without control, you may probably introduce some practices that aren't good for ESLint. For example, one of the most simple things like checking that some object has a specific property:

let events = {"some-index": false};
let key = "some-index";

if(events.hasOwnProperty(key)){
    // Do Something ...
    console.log("The object has the property");
}

This would trigger the mentioned exception when you try to build your application, because of the no-prototype-builtins rule. In ECMAScript 5.1, the Object.create method was added, which enables the creation of objects with a specified [[Prototype]]. Object.create(null) is a common pattern used to create objects that will be used as a Map. This can lead to errors when it is assumed that objects will have properties from Object.prototype. The rule no-prototype-builtins prevents calling Object.prototype methods directly from an object. For more information about the no-prototype-builtins, please visit the official documentation of ESLint here.

In this article, I will share with you different ways to avoid this error from appearing when trying to build your application.

Solutions

There are multiple ways to circumvent this error, the first one is to simply access the hasOwnPropertyMethod from the prototype of Object and execute the function using call:

let events = {"some-index": false};
let key = "some-index";

if(Object.prototype.hasOwnProperty.call(events, key)) {
    // This would compile without any issue !
    console.log("The object has the property");
}

An equivalent way to check if the object has the property, as long as you haven't done anything to make the properties not enumerable:

let events = {"some-index": false};
let key = "some-index";

if({}.propertyIsEnumerable.call(events, key)) {
    // This would compile without any issue !
    console.log("The object has the property");
}

Or through the getOwnPropertyDescriptor method:

let events = {"some-index": false};
let key = "some-index";

if(!!Object.getOwnPropertyDescriptor(events, key)) {
    // This would compile without any issue !
    console.log("The object has the property");
}

Happy coding ❤️!


Senior Software Engineer at Software Medico. Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.

Sponsors