Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array prototype is read only, properties should not be added no-extend-native

So basically I have this code:

Array.prototype.inState = function (needle, haystack) {
  let index = this.findIndex(value => value[needle] === haystack);

  return index === -1;
};

and it works fairly enough to check if the given needle is exists in the react state or not. but ESlint keep saying that:

Array prototype is read only, properties should not be added  no-extend-native

so my question is: What is wrong with my code ?

like image 930
AH.Pooladvand Avatar asked Nov 20 '18 07:11

AH.Pooladvand


2 Answers

From EsLint Docs:

In JavaScript, you can extend any object, including builtin or “native” objects. Sometimes people change the behavior of these native objects in ways that break the assumptions made about them in other parts of the code.

For example here we are overriding a builtin method that will then affect all Objects, even other builtin.

// seems harmless
Object.prototype.extra = 55;

// loop through some userIds
var users = {
    "123": "Stan",
    "456": "David"
};

// not what you'd expect
for (var id in users) {
    console.log(id); // "123", "456", "extra"
}

In-short, Array.prototype.inState will extend the array.prototype and hence whenever you want to use an array, the instate function will be added to that array too.

So, in your case this example will be applied to array.

Array.prototype.inState = function (needle, haystack) {
  let index = this.findIndex(value => value[needle] === haystack);

  return index === -1;
};


// loop through some userIds
var users = [{"123": "Stan"},{"456": "David"}];

// not what you'd expect
for (var id in users) {
    console.log(users[id]); // "123", "456", "extra"
}

WorkAround


You can add this line to ignore warning.

/*eslint no-extend-native: ["error", { "exceptions": ["Object"] }]*/ to ignore that warning.

Ref: https://eslint.org/docs/rules/no-extend-native

like image 96
Just code Avatar answered Oct 23 '22 01:10

Just code


Its because esLint gets it mutation to the native protoTypes chain. You can add // eslint-disable-next-line no-extend-native in above the line it should be fine.

like image 34
Ashif Zafar Avatar answered Oct 23 '22 02:10

Ashif Zafar