JavaScript: What dangers are in extending Array.prototype?

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?


Solution 1:

Most people missed the point on this one. Polyfilling or shimming standard functionality like Array.prototype.filter so that it works in older browsers is a good idea in my opinion. Don't listen to the haters. Mozilla even shows you how to do this on the MDN. Usually the advice for not extending Array.prototype or other native prototypes might come down to one of these:

  1. for..in might not work properly
  2. Someone else might also want to extend Array with the same function name
  3. It might not work properly in every browser, even with the shim.

Here are my responses:

  1. You don't need to use for..in on Array's usually. If you do you can use hasOwnProperty to make sure it's legit.
  2. Only extend natives when you know you're the only one doing it OR when it's standard stuff like Array.prototype.filter.
  3. This is annoying and has bit me. Old IE sometimes has problems with adding this kind of functionality. You'll just have to see if it works in a case by case basis. For me the problem I had was adding Object.keys to IE7. It seemed to stop working under certain circumstances. Your mileage may vary.

Check out these references:

  • http://perfectionkills.com/extending-native-builtins/
  • http://blip.tv/jsconf/jsconf2011-andrew-dupont-everything-is-permitted-extending-built-ins-5211542
  • https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/filter
  • https://github.com/kriskowal/es5-shim

Good luck!

Solution 2:

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:

  • Dependability: "The simple explanation is that an enterprise software product needs a consistent and dependable execution environment to be maintainable."
  • Incompatible implementations: "Another peril of modifying objects that you don’t own is the possibility of naming collisions and incompatible implementations."
  • What if everyone did it?: "Simply put: if everyone on your team modified objects that they didn’t own, you’d quickly run into naming collisions, incompatible implementations, and maintenance nightmares."

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.

Solution 3:

As a modern update to Jamund Ferguson's answer:

Usually the advice for not extending Array.prototype or other native prototypes might come down to one of these:

  1. for..in might not work properly
  2. Someone else might also want to extend Array with the same function name
  3. It might not work properly in every browser, even with the shim.

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.

// Any string works but a namespace may make library code easier to debug. 
var myMethod = Symbol('MyNamespace::myMethod');

Array.prototype[ myMethod ] = function(){ /* ... */ };

var arr = [];

// slightly clumsier call syntax
arr[myMethod]();

// Also works for objects
Object.prototype[ myMethod ] = function(){ /* ... */ };

Pros:

  • For..in works as expected, symbols aren't iterated over.
  • No clash of method names as symbols are local to scope and take effort to retrieve.

Cons:

  • Only works in modern environments
  • Slightly clunky syntax

Solution 4:

Extending Array.prototype in your own application code is safe (unless you use for .. in on arrays, in which case you need to pay for that and have fun refactoring them).

Extending native host objects in libraries you intend others to use is not cool. You have no right to corrupt the environment of other people in your own library.

Either do this behind an optional method like lib.extendNatives() or have [].filter as a requirement.

Extending Natives and Host Objects

Solution 5:

Prototype does this. It's evil. The following snippet demonstrates how doing so can produce unexpected results:

<script language="javascript" src="https://ajax.googleapis.com/ajax/libs/prototype/1.7.0.0/prototype.js"></script>
<script language="javascript">
  a = ["not", "only", "four", "elements"];
  for (var i in a)
    document.writeln(a[i]);
</script>

The result:

not only four elements function each(iterator, context) { var index = 0; . . .

and about 5000 characters more.