Sub topic 18
Built-in Prototypes and Why You Should Not Modify Them
This chapter assumes you know how the prototype chain resolves property lookups, how Object.hasOwn and for...in treat inherited properties, and how constructor functions use their prototype property. Everything here applies those ideas to the objects JavaScript gives you for free.
Built-in Objects Use the Same Mechanism
Arrays, functions, dates, and regular expressions get their methods the same way your own objects do. Array, Function, Date, and Object are constructor functions. Each one has a prototype object that holds the shared methods. When you write [1, 2, 3].map(...), the engine does not find map on the array. It finds map on Array.prototype.
const arr = [1, 2, 3];
console.log(Object.getPrototypeOf(arr) === Array.prototype); // true
console.log(Object.getPrototypeOf(Array.prototype) === Object.prototype); // true
console.log(Object.getPrototypeOf(Object.prototype)); // null
console.log(Object.hasOwn(arr, 'map')); // false
console.log(Object.hasOwn(Array.prototype, 'map')); // true
function greet() {}
console.log(Object.getPrototypeOf(greet) === Function.prototype); // true
console.log(Object.getPrototypeOf(Function.prototype) === Object.prototype); // trueNearly every chain ends at Object.prototype. That is why toString, hasOwnProperty, and valueOf show up on arrays, functions, and plain objects alike.
Primitives Borrow Prototypes Too
Strings, numbers, and booleans are primitives, so they have no properties of their own. When you call 'abc'.toUpperCase(), the engine temporarily wraps the primitive in a String object and looks the method up on String.prototype. So a change to String.prototype reaches every string literal in the program.
Built-in Methods Are Non-Enumerable
Built-in methods are defined with enumerable: false. This is why for...in over an array lists only the indexes and not map or filter:
const desc = Object.getOwnPropertyDescriptor(Array.prototype, 'map');
console.log(desc.enumerable); // false
console.log(desc.writable); // true
console.log(desc.configurable); // trueThe descriptor shows that Array.prototype.map is writable and configurable. Nothing in the language stops you from replacing or adding methods on built-in prototypes. The rest of this chapter explains why you should not do it anyway.
Why Extending Built-ins Is Tempting
Adding a method to a built-in prototype makes it available everywhere at once:
Array.prototype.last = function () {
return this[this.length - 1];
};
console.log([10, 20, 30].last()); // 30This reads nicely. But you have just changed a shared object for every array in the whole program, including arrays created by libraries you did not write. The prototype is global state.
What Goes Wrong
Enumeration Leaks
Plain assignment creates an enumerable property. Any code that uses for...in on an array, or on an object if you patched Object.prototype, now sees your method:
Array.prototype.last = function () {
return this[this.length - 1];
};
const nums = [10, 20];
for (const key in nums) {
console.log(key); // '0', '1', 'last'
}
delete Array.prototype.last; // clean upCode that worked yesterday now loops over an extra key and may call it or serialize it.
Collisions with Future Standards
The language keeps adding methods to built-ins. If a library defines a method with the same name but different behavior, one of two things happens. The library overwrites the standard method and breaks code that expects the standard behavior, or the standard committee has to pick a worse name. Both have happened:
- MooTools added
Array.prototype.contains. The proposed standard method was renamed toincludesbecausecontainswould have broken existing websites. - MooTools also added a
flattenmethod that behaved differently from the proposal. The committee renamed the standard method toflat. This episode is sometimes called "smooshgate", after a joke proposal to name itsmoosh.
Collisions Between Libraries
Two libraries can each add Array.prototype.last, one returning the last element and the other returning the last n elements. Whichever loads second wins, and the other library breaks in ways that are hard to trace.
| Problem | Cause | Symptom |
|---|---|---|
| Enumeration leak | Assignment creates an enumerable property | Extra keys in `for...in` loops |
| Standards collision | Your name matches a future built-in | Native method replaced, or other code breaks on upgrade |
| Library collision | Two scripts patch the same name | Behavior depends on load order |
| Hidden dependency | Code relies on a global patch | Module fails when moved to a project without the patch |
| Prototype pollution | Untrusted input writes to `Object.prototype` | Every object gains attacker-controlled properties |
Prototype Pollution: The Security Version
Prototype pollution happens when untrusted data ends up writing to Object.prototype. A common source is a naive recursive merge:
function merge(target, source) {
for (const key in source) {
const value = source[key];
if (typeof value === 'object' && value !== null) {
if (typeof target[key] !== 'object' || target[key] === null) {
target[key] = {};
}
merge(target[key], value);
} else {
target[key] = value;
}
}
return target;
}
const payload = JSON.parse('{"__proto__": {"isAdmin": true}}');
merge({}, payload);
console.log({}.isAdmin); // true — every object is now "admin"
delete Object.prototype.isAdmin; // clean upJSON.parse creates an ordinary own property named __proto__. Inside merge, target['__proto__'] goes through the __proto__ accessor and returns Object.prototype, so the recursive call writes isAdmin onto it. To defend against this, skip the keys __proto__, constructor, and prototype, iterate only own keys with Object.keys, or merge into null-prototype objects (covered in the next chapter).
The Accepted Exception: Polyfills
A polyfill adds a standard method to environments that lack it, with the behavior the specification defines. A careful polyfill checks whether the method already exists and defines it as non-enumerable, matching native methods:
if (!Array.prototype.at) {
Object.defineProperty(Array.prototype, 'at', {
value: function at(index) {
let n = Math.trunc(index) || 0;
if (n < 0) n += this.length;
if (n < 0 || n >= this.length) return undefined;
return this[n];
},
writable: true,
enumerable: false,
configurable: true
});
}
console.log([1, 2, 3].at(-1)); // 3This is safe because the name and behavior already belong to the standard, so no future collision is possible. In practice, use a maintained polyfill package such as core-js rather than writing your own.
Better Alternatives
For non-standard helpers, keep the behavior local:
// A plain function: explicit, importable, no global effect
const last = (arr) => arr[arr.length - 1];
console.log(last([10, 20, 30])); // 30
// A subclass: the new method appears only on instances you create
class List extends Array {
last() {
return this[this.length - 1];
}
}
const list = List.from([1, 2, 3]);
console.log(list.last()); // 3
console.log([1, 2, 3].last); // undefinedExercise
A teammate adds Object.prototype.isEmpty = function () { return Object.keys(this).length === 0; };. Name two concrete things that can break, and suggest a replacement.
Show answer
First, the method is enumerable, so every for...in loop over any object now includes isEmpty, which breaks code that copies or serializes keys this way. Second, any object with its own isEmpty property, or a future standard method with that name, will conflict with it, and a library that patches the same name will overwrite it depending on load order. A replacement is a standalone function: const isEmpty = (obj) => Object.keys(obj).length === 0;.
Exercise
Why does for (const k in [1, 2]) console.log(k) print only "0" and "1", even though arrays inherit dozens of methods?
Show answer
for...in visits enumerable properties, both own and inherited. The methods on Array.prototype and Object.prototype are defined with enumerable: false, so the loop skips them. A method added by plain assignment would be enumerable and would appear.
Exercise
Is a polyfill that writes Array.prototype.at = function (i) { ... } with no existence check acceptable? What would you change?
Show answer
It is risky. It overwrites the native implementation in engines that already have one, and plain assignment makes the method enumerable. Wrap it in if (!Array.prototype.at) and define it with Object.defineProperty and enumerable: false. A maintained polyfill library is better still.