Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

This question already has an answer here:

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?

share|improve this question

marked as duplicate by Dancrumb, Qantas 94 Heavy, Morten Kristensen, chrylis, jaypal singh Feb 22 '14 at 0:07

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

1 Answer 1

up vote 3 down vote accepted

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.

share|improve this answer
    
"extending Array and then modifying THAT" While your answer isn't bad, that isn't as easy as you make it out to be, unless I'm missing something... ;) –  Qantas 94 Heavy Feb 21 '14 at 23:58
    
Oh it's definitely not THAT easy don't get me wrong, but it IS doable; a well-explained example can be seen at bennadel.com/blog/… –  moberemk Feb 22 '14 at 3:08
    
The issue with that is that it isn't a real array -- it just has all the prototype methods. For example, the length property doesn't update like a real array, unless you use the add method that's provided. –  Qantas 94 Heavy Feb 22 '14 at 3:11

Not the answer you're looking for? Browse other questions tagged or ask your own question.