Extending Array prototype in JavaScript

javascript

Solution

Generally speaking you should avoid extending base objects because it may clash with other extensions of that object. Ideally extending Array and then modifying THAT is the safest way to do things as it is guaranteed to not clash with other developers who might try to do the same thing (even though they shouldn't).

Basically, avoid extending base objects when possible because it can get you into trouble for very little real benefit compared to extending the array object.

Problem

I often found myself wanting to do certain operations for all the items in an array and I wished that JavaScript had something like C#'s LINQ. So, to that end, I whipped up some extensions of the Array prototype: ``` var data = [1, 2, 3]; Array.prototype.sum = function () { var total = 0; for (var i = 0; i < this.length; i++) { total += this[i]; } return total; }; Array.prototype.first = function () { return this[0]; }; Array.prototype.last = function () { return this[this.length - 1]; }; Array.prototype.average = function () { return this.sum() / this.length; }; Array.prototype.range = function () { var self = this.sort(); return { min: self[0], max: self[this.length-1] } }; console.log(data.sum()) <-- 6 ``` This makes working with arrays much easier if you need to do some mathematical processing on them. Are there any words of advice against using a pattern like this? I suppose I should probably make my own type that inherits from Array's prototype, but other than that, if these arrays will only have numbers in them is this an OK idea?

Original source

Related problems