0

I was writing something and in my research found that arrays are documented to have map/reduce/filter, but not in IE ?8? or older. So I poked around, found JavaScript: What dangers are in extending Array.prototype?, and besides several responses to cool my enthusiasm for extending Array.prototype (perhaps even as a shim), the accepted response said:

...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.

So, in other words, my use case was to shim for older IE was a mechanism that may be dodgy in older IE.

So if I want to support old IE, I should make and use my own standalone map / reduce / filter? I'm planning on taking a different approach in what I am writing now, but it would be nice to know for reference's sake, "If I want feature X that is not in browser Y, and shims may break in browser Y, what is the preferred approach?"

Community
  • 1
  • 1
Christos Hayward
  • 5,777
  • 17
  • 58
  • 113
  • Try it and see. It's probably more common to instead create a collection of methods that use the native method if it's available, else, use a custom built method. underscore.js and jQuery uses that technique. – Kevin B Jan 16 '15 at 15:33

2 Answers2

2

I don't see anything wrong with extending natives, as long as it's done correctly:

if(!Array.prototype.map) {
  Array.prototype.map = //your shim
}

This way, you're not clobbering native methods that already exist.

Just make sure your shims stay up to date with the spec/current implementations otherwise you'll run into some very confusing bugs.

Adam Jenkins
  • 51,445
  • 11
  • 72
  • 100
0

If you specifically are trying to add es5 array functions like map, reduce, filter, etc. then you can use the es5-shim library which will add shims for a variety of es5 features including those array functions and works in older versions of IE.

David Risney
  • 3,886
  • 15
  • 16