Saturday, August 29, 2009

why you should not add stuff to Array.prototype in javascript


Why should methods not be added to the Array prototype in Javascript? The main reason is they break associative arrays, those where the index you use does not need to be a number, but could be anything. Kinda like a hash. 

With an associative array you can do stuff like


for (item in array)
alert(array[item])


Methods added to arrays prototype will show you up in the for a in b call. Here's an example




Array.prototype.eachIndex = function(func) {
for (item in this)
{
func(item)
}
}

function bar() {
a = [1,2,3]
div = document.getElementById('foo')
a.eachIndex(function (i){div.innerHTML += ' ' + i + ' : ' + a[i] + "

"})
}


Whats in a?


So there, I hope you've learnt your lesson!! Ofcourse you could decide associative arrays are pointless and I can manage with javascript objects thank you very much :). Did you notice peek which has been added to the array, presumably by blogger?

4 comments:

  1. Hey Vishnu,

    What you describe is an issue for
    Associative Arrays (Object.prototype) but not Arrays (Array.prototype). Your actual issue is your eachIndex method is badly implemented it should be using index access via a standard for loop. This will fix you problem and actually be faster.

    Array.prototype.each = function(handler) {
    for(var i=0; i<this.length; i++){
    handler(this[i], i);
    }
    }

    Javascript 1.5 actually added a function called every very similar to the above (just without the optional index value)
    See https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/every

    As you can see this is justed added to the prototype as well.

    Hope that clears it up

    ReplyDelete
  2. very cool & good tip, thank you very much for sharing.

    Can I share this snippet on my JavaScript library?


    Awaiting your response. Thank

    ReplyDelete