Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
146
rated 0 times [  151] [ 5]  / answers: 1 / hits: 73368  / 15 Years ago, mon, february 15, 2010, 12:00:00

Given a simple zero based, numerically indexed array:



var list = ['Foo', 'Bar', 'Baz'];


Many times, I have noticed that when someone suggests looping through variables in an array like this:



for(var item in list) { ... }


...there's almost certainly someone suggesting that that's bad practice and suggests an alternative approach:



var count = list.length;

for(var i = 0; i < count; i++) {
var item = list[i];
...
}


What's the reasoning for not using the simpler version above and to use the second example instead?


More From » arrays

 Answers
62

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)

[#97569] Friday, February 12, 2010, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jazlynnessencec

Total Points: 434
Total Questions: 113
Total Answers: 94

Location: Norway
Member since Mon, May 23, 2022
2 Years ago
;