Wednesday, January 29, 2014

Extending Javascript Array

It's surprising to some that Javascript has all sort of methods to manipulate Arrays but none of these (in current specs.) allows to quickly find Max/Min values stored in array. Sometimes its tempting to quickly extend native JS Array. So having array e.g.:

var beersDrunk=[22,33,44,32,1];

We trying to find max value stored in this array. One option is to add (static) max() method to Array below:

Array.max=function(v) {
    return Math.max.apply(this,v);
};


This will allow us to call:

Array.max(beersDrunk); // returns 44

Or other way you can define max() on Array's prototype as:

Array.prototype.max=function() {
    return Math.max.apply(this,this);
};


This allows you to call max() method directly on the Array's object itself e.g.:

beersDrunk.max(); // returns 44

If you think "cool, lets use it in my code!" beware.., its not bulletproof method and has obvious problems. It will fail (return NaN) if array contains anything else then numbers e.g. [22,"boom",44,32,1], its not the fastest way to look up Max/Min values etc. etc. Probably the worst however is that monkey patching like this breaks encapsulation. Imagine if at some point ECMAScript committee decides to add max() method to Javascript Array. Your implementation will override theirs and booom, this might cause serious problems. Extending array's prototype will also give you more headaches if you are using  (dont!) for in  to iterate over arrays. This is a huge topic and luckily for all of us there are ton's of resources all over the web on problems of extending native Javascript objects. It might be worth googling the topic if you decide to use this method in your code.

Despite all the problems it is interesting method nonetheless. If nothing else, being able to understand how the code above works will make you a better programmer.

No comments:

Post a Comment