Why shouldn't JavaScript object prototype be modified

Find out why JavaScript object prototypes should not be modified and what to do

As programmers, one of the first skills we must learn is how to find solutions.

Google is your friend. In most cases, StackOverflow answers since 2009 are the perfect solutions to the problems above 2019.

On that particular site or personal blog, I sometimes see code to modify the prototype of the built-in Objects.

Like this example, by adding ainsertmethod:

Array.prototype.insert = function(index, item) {
  this.splice(index, 0, item)
}

This way, you can have any array and call insert() on it:

['red', 'blue'].insert(0, 'yellow')

It is convenient that you don't have to define such functions and worry about their scope, you can attach them to the Array object so that every array is available.

Just because of youwere ableDoes not mean youshould.

What's wrong with this method?

Possible conflict

Assume that the library you use implements this kind of thing. The same is true for the other library you imported. Maybe these methods work slightly differently, until everything is normal, everything seems to work fine.

You have a big problem here because you cannot modify these libraries, but you still want to use them.

Verify your code in the future

Assuming that the next JavaScript version implementsArray.insertmethod. Have different signatures. What will happen now? You need to go back and rewrite all the code you wrote. Maybe for the customer, you don't work anymore.

Or maybe you are doing this in a library that others use in your own project. That would be worse.

This method will only generate technical debt and will almost cause problems.

What should you do?

Create a function in the library file and import it when you want to use it. Do not modify objects that you cannot control.

Download mine for freeJavaScript beginner's manual


More js tutorials: