Skip to content

Using Prototypes with Arrays

Every array inherits its methods, such as map(), filter() and sort(), from Array.prototype. Because the prototype is shared, a method added to it becomes available on every array in the program at once. That is powerful, but changing a built-in prototype has costs, so this page shows how it works and then the safer ways to get the same result.

An array does not hold its own copy of map(). The method is found on its prototype:

const scores = [7, 3, 9];
console.log(Object.hasOwn(scores, 'map'));
console.log(scores.map === Array.prototype.map);
console.log(Object.getPrototypeOf(scores) === Array.prototype);

This prints:

false
true
true

Assigning a function to Array.prototype gives every array a new method. Inside it, this is the array that the method was called on:

Array.prototype.total = function () {
return this.reduce((sum, n) => sum + n, 0);
};
const prices = [2.5, 4, 1.25];
console.log(prices.total());
for (const key in prices) {
console.log(key);
}

This prints:

7.75
0
1
2
total

The method works, but the for...in loop has picked it up too, because a property created by assignment is enumerable and for...in visits inherited enumerable properties. Defining it with Object.defineProperty() and enumerable: false hides it from the loop, as the built-in methods are hidden:

Object.defineProperty(Array.prototype, 'total', {
value: function () {
return this.reduce((sum, n) => sum + n, 0);
},
writable: true,
configurable: true,
enumerable: false,
});
const prices = [2.5, 4, 1.25];
console.log(prices.total());
for (const key in prices) {
console.log(key);
}

This prints:

7.75
0
1
2

Even when hidden from loops, a method added to a built-in prototype affects every script on the page, including libraries you did not write. Two scripts can add methods with the same name that behave differently, and a name you choose today may be added to the language later with different behaviour. This has happened: an old library’s Array.prototype.flatten forced the standard method to be named flat() instead. The one accepted use is a polyfill, which adds a standard method to an older engine that lacks it and matches the specification exactly; see Creating Polyfills.

A plain function does the same job without touching anything shared. This one shuffles a copy of an array with the Fisher–Yates algorithm, which gives every order an equal chance:

function shuffled(items) {
const copy = [...items];
for (let i = copy.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[copy[i], copy[j]] = [copy[j], copy[i]];
}
return copy;
}
const tasks = ['email', 'gym', 'shopping', 'laundry', 'reading'];
console.log(shuffled(tasks));
console.log(tasks);

One run printed the following, and the first line differs each time:

[ 'laundry', 'gym', 'reading', 'email', 'shopping' ]
[ 'email', 'gym', 'shopping', 'laundry', 'reading' ]

The original array is unchanged, because the function works on a copy. A common shortcut, items.sort(() => Math.random() - 0.5), is biased towards some orders and also changes the array in place, so it is best avoided.

If you want the method-call style, extend Array with a class of your own. Only instances of that class get the new method, and built-in methods such as filter() return instances of the subclass, so calls can be chained:

class NumberList extends Array {
total() {
return this.reduce((sum, n) => sum + n, 0);
}
}
const prices = NumberList.from([2.5, 4, 1.25]);
console.log(prices.total());
const dear = prices.filter((p) => p > 2);
console.log(dear instanceof NumberList, dear.total());
console.log(typeof [1, 2].total);

This prints:

7.75
true 6.5
undefined

Ordinary arrays are left alone, which is what the last line shows.

Steve Griffith covers this topic in his video Practical Uses for Prototypes with Arrays.