Sub topic 17
Built-in Prototypes and Why You Should Not Modify Them
This chapter assumes you know how the prototype chain is walked during lookup, how Object.create sets a prototype, and how Object.hasOwn differs from the in operator and for...in.
Built-in Objects Use the Same Chain
Arrays, functions, dates, and plain objects get their methods the same way your own objects do: through [[Prototype]] links. An array literal is linked to Array.prototype. Array.prototype is linked to Object.prototype, and the chain ends at null.
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')); // trueWhy Modifying Built-in Prototypes Causes Trouble
Built-in prototypes are ordinary objects, so you can add methods to them. Doing so is called monkey patching. It is discouraged for three reasons.
| Problem | What goes wrong |
|---|---|
| Future collisions | A later standard may add a method with the same name but different behavior. Old libraries that patched `Array.prototype.flatten` and `contains` forced the standard to rename those methods to `flat` and `includes`. |
| Library conflicts | Two scripts that patch the same name overwrite each other. Whichever loads last wins. |
| Enumeration leaks | A property added by assignment is enumerable, so it appears in every `for...in` loop. |
Here is the enumeration leak in action:
Object.prototype.extra = 'oops';
const user = { name: 'Ada' };
for (const key in user) {
console.log(key); // "name", then "extra"
}
delete Object.prototype.extra; // clean upObjects Without a Prototype: Object.create(null)
A plain {} inherits from Object.prototype. When you use an object as a dictionary, the inherited names get in the way:
const counts = {};
console.log('constructor' in counts); // true, though you never set it
console.log(counts.toString); // [Function: toString]If keys come from user input, words like constructor, toString, or __proto__ give wrong answers or change the object's behavior. Object.create(null) makes an object whose prototype is null, so it inherits nothing:
const dict = Object.create(null);
dict.apple = 3;
dict.__proto__ = 'just a key'; // stored as an ordinary own property
console.log(Object.getPrototypeOf(dict)); // null
console.log(dict.toString); // undefined
console.log('toString' in dict); // false
console.log(Object.keys(dict)); // ['apple', '__proto__']The trade-off is that the object has none of the usual methods. String(dict) throws a TypeError because the object has no toString, and dict.hasOwnProperty does not exist. Use the static helpers Object.hasOwn(dict, key) and Object.keys(dict) instead.
Exercise
You run const words = {}; words.constructor = (words.constructor || 0) + 1; to count the word "constructor". What does words.constructor hold afterward, and how do you fix it?
Show answer
words.constructor is the string "function Object() { [native code] }1". The lookup found the inherited Object function, which is truthy, and adding 1 to it concatenated a string. Fix it by creating the counter with Object.create(null) (or a Map), so the lookup returns undefined and the count starts at 1.
Exercise
Why does adding Array.prototype.last = function () { return this[this.length - 1]; } risk breaking code in the future, even if it works today?
Show answer
A future standard could add a last method with different behavior, and your patch would override it for every script on the page. Other libraries could also define last differently, and the assignment creates an enumerable property that shows up in for...in loops over arrays.