Tuesday, May 21, 2024
 Popular · Latest · Hot · Upcoming
4
rated 0 times [  8] [ 4]  / answers: 1 / hits: 17907  / 6 Years ago, tue, november 20, 2018, 12:00:00

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 ?


More From » reactjs

 Answers
51

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


[#53079] Friday, November 16, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
soniap

Total Points: 626
Total Questions: 119
Total Answers: 110

Location: Palestine
Member since Tue, Jul 20, 2021
3 Years ago
;