JavaScriptMedium
Why is extending built-in objects a bad idea?
By FrontendPro Editorial Team Updated 9/26/2026
#JavaScript
Answer
Adding methods to Array.prototype, Object.prototype and friends is called monkey patching. It works, and it is a bad idea because the prototype is shared by every piece of code on the page — yours, your libraries', and whatever runs next year.
js
Array.prototype.last = function () { return this[this.length - 1]; };
[1, 2, 3].last(); // 3 — looks lovely
What goes wrong
- Collisions. Two libraries both define
.last, with different semantics. The one that loads second wins and the other breaks, silently and far from the cause. - Future collisions.
Array.prototype.flattenwas proposed, then renamed toflatand delayed, specifically because a widely used library had patchedflattenincompatibly. Your name today may be a standard method tomorrow. for...inleaks. An enumerable addition toObject.prototypeshows up in everyfor...inloop in the program, including inside dependencies you do not control.
js
Object.prototype.mine = 1;
for (const k in { a: 1 }) console.log(k); // 'a', then 'mine'
- Code that lies. A reader seeing
arr.last()has no way to know it is not standard. There is nothing to grep for and nothing to import. - Engine deoptimisation and broken
Object.freezeassumptions, and host objects likeElementare not guaranteed patchable across browsers.
What to do instead
js
const last = arr => arr[arr.length - 1]; // a plain function
class Stack extends Array {} // subclass, if you need methods
A standalone function is explicit, importable, tree-shakeable, and testable. If a method really must exist, subclass rather than patch the prototype.
The one exception
A polyfill is legitimate monkey patching: it implements a specified method under its specified name, and guards on absence.
js
if (!Array.prototype.at) {
Object.defineProperty(Array.prototype, 'at', {
value: function (i) { ... },
writable: true, configurable: true, enumerable: false // note: not enumerable
});
}
