Google JavaScript Style Guide advises against extending the Array.prototype
.
However, I used Array.prototype.filter = Array.prototype.filter || function(...) {...}
as a way to have it (and similar methods) in browsers where they do not exist. MDN actually provides similar example.
I am aware about Object.prototype
issues, but Array
is not a hash table.
What issues may arise while extending Array.prototype
that made Google advise against it?
You can easily create somekind of sandbox with
poser
library.Take a look on https://github.com/bevacqua/poser
Extending the prototype is a trick that only works once. You do and you use a library that also does it (in an incompatible way) and boom!
I'll give you the bullet points, with key sentences, from Nicholas Zakas' excellent article Maintainable JavaScript: Don’t modify objects you don’t own:
Basically, don't do it. Even if your project is never going to be used by anyone else, and you're never going to import third party code, don't do it. You'll establish a horrible habit that could be hard to break when you start trying to play nice with others.
As a modern update to Jamund Ferguson's answer:
Points 1. and 2. can now be mitigated in ES6 by using a Symbol to add your method.
It makes for a slightly more clumsy call structure, but adds a property that isn't iterated over and can't be easily duplicated.
Pros:
Cons:
Some people use
for ... in
loops to iterate through arrays. If you add a method to the prototype, the loop will also try to iterate over that key. Of course, you shouldn't use it for this, but some people do anyway.Prototype does this. It's evil. The following snippet demonstrates how doing so can produce unexpected results:
The result:
and about 5000 characters more.