Assigning a function to Array.prototype.name gives every array that method, because arrays look methods up on their prototype, and inside it this is the array. A careful version uses Object.defineProperty so the method is non-enumerable like the built-ins (otherwise it appears in every for...in loop) and refuses to overwrite a name that already exists. The answer interviewers are listening for is why you usually shouldn't: the prototype is shared by all code on the page, and a library's Array.prototype.flatten is why the standard method is called flat. Prefer a subclass (class Stack extends Array, with Symbol.species if needed) or a plain function.
Implement a function which extends Array.prototype.
Answer it out loud, in your own words. Then compare.
Interviewers listen for how you get there, not only where you land. The answer opens once you have tried.
Every array inherits from Array.prototype, so a function placed there is callable on all arrays, with this bound to the array. It must be a regular function, not an arrow. The last check shows the cost: an assigned method is enumerable, so for...in over any array now lists it.
// A method every array gets, because arrays look methods up on Array.prototype.Array.prototype.last = function () {return this[this.length - 1];};Array.prototype.sum = function () {return this.reduce((total, x) => total + x, 0);};
passes 3 checks run on every build, against the native method where there is one
- every array gets the method
- this is the array it was called on
- the problem: it shows up in for...in
Object.defineProperty with enumerable: false (and writable/configurable true, matching the built-ins' descriptors) keeps the method out of for...in and object spreads. Checking hasOwnProperty first means you never silently replace a standard method or another library's, which is how prototype extensions break pages.
// Add a method the way the built-ins are defined: not enumerable (so for...in and object spreads// don't show it), and only if nothing is there already.function extendArray(name, fn) {if (Object.prototype.hasOwnProperty.call(Array.prototype, name)) {throw new Error(`Array.prototype.${name} already exists`); // never overwrite: it may be a standard method}Object.defineProperty(Array.prototype, name, {value: fn,writable: true,configurable: true,enumerable: false,});}extendArray('last', function () {return this[this.length - 1];});extendArray('sum', function () {return this.reduce((total, x) => total + x, 0);});
passes 3 checks run on every build, against the native method where there is one
- methods work and stay hidden from for...in
- described like a built-in
- refuses to overwrite an existing method
class Stack extends Array gives real arrays (Array.isArray is true, length and push work) with extra methods, and leaves every other array alone. Methods like map build their result with the constructor named by Symbol.species; returning Array there makes them hand back plain arrays rather than Stacks. Plain functions (last(xs)) need no prototype at all and can't collide with a future standard method.
// Better than touching the shared prototype: a subclass, which changes only its own instances.class Stack extends Array {peek() {return this[this.length - 1];}get isEmpty() {return this.length === 0;}// map, filter and slice on a Stack build their result with this constructor. Returning Array// makes them hand back plain arrays instead of Stacks.static get [Symbol.species]() {return Array;}}// Or no prototype at all: plain functions, which tree-shake and can't collide with the standard.const last = (xs) => xs[xs.length - 1];const sum = (xs) => xs.reduce((total, x) => total + x, 0);
passes 4 checks run on every build, against the native method where there is one
- a subclass adds methods without touching Array.prototype
- Symbol.species makes map and filter return plain arrays
- push and length work as on any array
- plain functions do the same job
SmooshGate
TC39 couldn't ship Array.prototype.flatten because MooTools had defined its own, and changing it would break sites still using that library. The standard method became flat; contains became includes for a similar reason.
Prototype pollution
Code that writes to shared prototypes from user-controlled keys (obj[key] = value with key = '__proto__') is a known vulnerability class: one write changes behaviour for every object.
Polyfills are the legitimate case
Polyfills do extend built-in prototypes, but only to add a standard method an old browser lacks, defined non-enumerable and only if missing, exactly like the intermediate stage.
Defining the method with an arrow function:
thisisn't the array.Plain assignment, which makes the method enumerable and breaks
for...inloops elsewhere.Overwriting an existing or future standard method with different behaviour.
Extending the prototype in library code, where it changes arrays in the app that uses the library.
Why do map and filter on a subclass return the subclass?
They create their result with ArraySpeciesCreate, which uses this.constructor[Symbol.species]. For a subclass that's the subclass itself, unless it overrides Symbol.species.
Is it ever fine to extend built-in prototypes?
In application code you fully control, with names unlikely to be standardised, it works, but polyfilling standard methods is the only widely accepted use.
How would TypeScript know about the new method?
Declaration merging: declare global { interface Array<T> { last(): T | undefined } } in a module, next to the implementation.
- developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain
- developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty
- developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/species
- developer.chrome.com/blog/smooshgate
- tc39.es/ecma262/#sec-arrayspeciescreate