Yes, there are reasons to not do this, one that immediately jumps out is that you will inevitably collide with another library that also thinks it is easier to adjust built-in prototypes.
Consider the following:
// my-cool-library.js
// Returns the last value in an array
Array.prototype.last = function() {
return this[this.length - 1];
}
// some-other-cool-library.js
// Returns the last possible index of the array
Array.prototype.last = function() {
return this.length - 1;
}
// some-consumer.js
import "my-cool-library.js";
import "some-other-cool-library.js";
const a = ["a", "b", "c"];
// You would probably expect it to print "c", but it prints 2
console.log(a.last());
You might think that this is unlikely, but what if you utilize really big frameworks? Let's say you use both Angular and lodash. It isn't all the unlikely that a huge framework like Angular would want to make life easier by adding some helper functions to certain Object prototypes. However, lodash is a very broad scoped library that also adds helper functions for just about every operation you might want to perform on a collection.
It is very likely that both of those libraries would want to use the same, terse helper function names but might not have the same function signature. Suddenly it becomes non-apparent how you should call and use Array.prototype.last
.
Instead, it is more appreciated when you leverage dependency injection and write functions that take all the arguments needed to perform the calculation and don't pollute the prototype. In that way, you get to decide exactly which last
function is used and when.
You can potentially also leverage the benefits of tree shaking.
Consider the non-polluting example:
// my-cool-library.js
// Returns the last value in an array
export function last(arr) {
return arr[arr.length - 1];
}
// some-other-cool-library.js
// Returns the last possible index of the array
export function last(arr) {
return arr.length - 1;
}
// some-consumer.js
import {last as myLast} from "my-cool-library.js";
import {last} from "some-other-cool-library.js";
const a = ["a", "b", "c"];
// You know that you're going to use myLast
// and how it is going to act
console.log(myLast(a));