Custom methods for arrays
Custom methods for arrays (Array.prototype override)
In JavaScript, arrays are objects, and all arrays inherit from Array.prototype. This means we can add new methods to all arrays.
Array.prototype.first = function () { return this[0]; }; const nums = [10, 20, 30]; console.log(nums.first()); // 10
Here we created a first() method that returns the first element of the array.
While technically possible, this is not considered good practice. Modifying Array.prototype affects all arrays and may cause unexpected bugs, especially when using third-party libraries.
Array.prototype.random = function () { return this[Math.floor(Math.random() * this.length)]; }; const a = [1, 2, 3]; for (let i in a) { console.log(i); // will also print "random" }
Safer alternative - use Object.defineProperty
Object.defineProperty(Array.prototype, 'random', { value: function () { return this[Math.floor(Math.random() * this.length)]; }, enumerable: false, // hides the method from `for...in` and `Object.keys` });
const getRandom = (arr) => { return arr[Math.floor(Math.random() * arr.length)]; }; getRandom([10, 20, 30]);
Composition is more predictable, easier to test, and doesn't alter global state.
✅ Good | ❌ Bad |
Composition/functions | Modifying Array.prototype |
Make invisible with Object.defineProperty | Omitting enumerable: false |
Scoped solutions | Global impact |
Object.defineProperty(Array.prototype, 'last', { value: function () { return this[this.length - 1]; }, enumerable: false, }); [1, 2, 3].last(); // 3
Adding methods to Array.prototype might be interesting for experimental or educational purposes, but in production environments it's recommended to avoid this. It's better to use regular functions, composition, or libraries.