Custom Methods for Arrays
In JavaScript, arrays are objects, and all arrays inherit from Array.prototype. This means we can add new methods to all arrays.
How to Add Custom Methods
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.
Why This Is Dangerous
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.
Dangerous Example
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`
});
Better Alternative - Composition
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.
Summary
| ✅ Good | ❌ Bad |
| Composition/functions | Modifying Array.prototype |
| Make invisible with Object.defineProperty | Omitting enumerable: false |
| Scoped solutions | Global impact |
Useful Custom Method Examples (potential use: when creating libraries)
Object.defineProperty(Array.prototype, 'last', {
value: function () {
return this[this.length - 1];
},
enumerable: false,
});
[1, 2, 3].last(); // 3
Conclusion
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.