Sunday, October 9, 2011

Javascript Array prototype and for-in

If you are developing a 3rd party application, a jQuery plugin or something similar, this will be specially useful for you.

I'm sure you've heard about it but you can extend the Javascript's core objects with the help of the prototype property. So, in this case let's see what happens if we combine Array.prototype with a for-in loop.

// let's create a simple array
var testArr = new Array(1, 2, 3);

// print it out to the console
for( var i in testArr ) {
 console.log(i+": "+testArr[i]);
}
// output: 
// 1
// 2
// 3

// extend the array object
Array.prototype.myMethod = function (arr) {
 // Do something here..
}

// loop the array again
for( var i in testArr ) {
 console.log(i+": "+testArr[i]);
}
// output: 
// 1
// 2
// 3 
// myMethod: function (arr) { }


As you can see, the second time in the loop the custom methos is also listed az an array item. This can be source of unknown bugs and I have spent a lot of time to figure this little trick out.

So, what are the solutions?
Use the Array object's "hasOwnProperty" property:
for( var i in arr) {
      if( !arr.hasOwnProperty( i ) ) continue;
      // stuff to do..
}

Or if you have jQuery loaded, use the .each method.
jQuery.each(testArr, function (key, value) {
 console.log(key+": "+value);
});


This possible bug source is kind of sneaky, yet the solution is simple :)

No comments:

Post a Comment