Why you should not modify a JavaScript object prototype
By Flavio Copes
Find out why modifying a built-in JavaScript prototype like Array.prototype causes library conflicts and breaks future-proofing, and what to do instead.
As programmers, one of the skills we must first learn is how to search for a solution.
Google is your friend. And a lot of the time a Stack Overflow answer from 2009 still looks like a perfect fix for a problem you hit today.
On that specific site, or on personal blogs, I sometimes see code that modifies built-in Objects prototypes.
Like in this example, where the Array object prototype is enhanced by adding an insert method:
Array.prototype.insert = function(index, item) {
this.splice(index, 0, item)
}
In this way, you can have any array and call insert() on it:
['red', 'blue'].insert(0, 'yellow')
It’s handy. Instead of having to define such function and worry about the scope of it, you attach it to the Array object, so that every array has it available.
But just because you can, it does not mean you should.
What’s wrong with this approach?
Possible conflicts
Suppose a library you use implements such thing. And another library you import does the same. Perhaps the methods work slightly differently, and things seem to work fine until they don’t.
You have a big problem here, because you can’t modify those libraries but you still want to use them.
Future-proofing your code
Suppose the next version of JavaScript implements an Array.insert method. With a different signature. Now what happens? You need to go back and rewrite all the code you wrote. Perhaps for a client you don’t work for anymore.
This is not hypothetical. ES2023 already added several Array methods: toSorted, toReversed, toSpliced, and with. Built-ins keep growing. Any name you stick on Array.prototype is a name the language (or a library) might want later.
Or maybe you did this in a library that’s used by other people in their own projects. That would be even worse.
This approach only creates technical debt and pretty much invites problems. Making the method non-enumerable with Object.defineProperty does not fix the conflict either: two packages can still fight over the same name.
What should you do instead?
Create a function in a library file and import it when you want to use it. Don’t modify objects you have no control over.
Want me to talk about your product? You can sponsor this site.
Related posts about js: