Monday, July 7, 2008

Good Practice for the use of for-in loop

As many people trying to extend the core javascript object, your code will have the risk and may broke somewhere because your for-in loop will loop through all properties including not-inherited properties. Consider this code:


//someone might extend funny methods from the global object
Object.prototype.hello = function() {
    return "hello";
};

//your code trying to count the number of properties or do something for your application
var object = {x: 5, y: 10};
var i = 0;
for(var property in object) {
    i++;
}
alert(i); // 3, you expect only 2 why it has three?


To solve this above problem, use hasOwnProperty("property") anywhere when you use for-in loop. hasOwnProperty() returns whether the pass-in property is inherited property or not.


var i = 0;
for(var property in object) {
    if(object.hasOwnProperty(property))
        i++;
}
alert(i); // 2, this is what expected

No comments:

Subscribe in a Reader