Why is ‘for(var item in list)’ with arrays considered bad practice in JavaScript?

First, the order of the loop is undefined for a for...in loop, so there’s no guarantee the properties will be iterated in the order you want.

Second, for...in iterates over all enumerable properties of an object, including those inherited from its prototype. In the case of arrays, this could affect you if your code or any library included in your page has augmented the prototype of Array, which can be a genuinely useful thing to do:

Array.prototype.remove = function(val) {
    // Irrelevant implementation details
};

var a = ["a", "b", "c"];

for (var i in a) {
    console.log(i);
}

// Logs 0, 1, 2, "remove" (though not necessarily in that order)

Leave a Comment