Javascript: expand prototypes

Javascript objects have a prototype. This prototype is itself an object. If an new object is created with “new”, the resulting object inherits the prototype of the “parent”, if the parent is a constructor.
So it’s possible to use a kind of object oriented programming (not really object orientated because things like encapsulation is not fully supported) without using classes. This procedure is called prototyping. You can copy new objects from prototypes and if you miss some functionality, you can expand the object on the fly or it’s prototype (inherhitance).


var abc = new Array();
//abc became a copy of Array.prototype

So let’s add some methods for calculating the summary and average to the standard javascript array.

(function() {
    //every new Array will have the sum method 
    Array.prototype.sum = function() {
        var sum = 0;
        for(var i = 0; i < this.length; i++)
            //add only if value is a number (isNaN means is not a number)
            sum += (isNaN(this[i])) ? 0 : this[i];
        return sum;
    //and avg method  
    Array.prototype.avg = function() {
        var length = 0;
        var sum = 0;
        for(var i = 0; i < this.length; i++)
            //only count if its a number
            sum += (isNaN(this[i])) ? 0 : this[i];
            length += (isNaN(this[i])) ? 0 : 1;
        return sum / length;
//create a new Array
var a = [1, 4, 3, "qwe", 9, 1, 6, 7];
//and calculate the sum and average
 * output:
 * 31 -> summary
 * 4.428571428571429 -> average

The benefit is now, that every Array got this methods. If you don’t had think about it before, it’s maybe a way to simplify your code in the future. Instead of writing the code for sum up an array anywhere, the array can handle this by itself.