Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 334
Tatu Ulmanen Avatar asked Feb 15 '10 10:02

Tatu Ulmanen


People also ask

Why is using for in with array iteration a bad idea?

Using for (var property in array) will cause array to be iterated over as an object, traversing the object prototype chain and ultimately performing slower than an index-based for loop. for (... in ...) is not guaranteed to return the object properties in sequential order, as one might expect.

Are for loops bad in JavaScript?

It is considered bad practice to use a for in loop in general and it should be avoided as much as possible. There are cases where it can't be avoid for instance if you are iterating though a JSON object, but this doesn't happen as often and generally you shouldn't be extending these types.

Can we use for in loop for arrays?

For Loop to Traverse Arrays. We can use iteration with a for loop to visit each element of an array. This is called traversing the array. Just start the index at 0 and loop while the index is less than the length of the array.

Should you use for in loop?

In general, you should use a for loop when you know how many times the loop should run. If you want the loop to break based on a condition other than the number of times it runs, you should use a while loop.


2 Answers

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) 
like image 157
Tim Down Avatar answered Sep 19 '22 18:09

Tim Down


Speed?

for(..;..;..) loop proved to be 36 times faster than for .. in when I tested it here.

Link courtesy this SO answer

like image 28
Amarghosh Avatar answered Sep 21 '22 18:09

Amarghosh