Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is using "for...in" for array iteration a bad idea?

I've been told not to use for...in with arrays in JavaScript. Why not?

like image 356
lYriCAlsSH Avatar asked Feb 01 '09 09:02

lYriCAlsSH


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.

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.

Can we use for in loop for array in JavaScript?

The for ... in syntax mentioned by others is for looping over an object's properties; since an Array in JavaScript is just an object with numeric property names (and an automatically-updated length property), you can theoretically loop over an Array with it.


1 Answers

The reason is that one construct:

var a = []; // Create a new empty array.  a[5] = 5;   // Perfectly legal JavaScript that resizes the array.    for (var i = 0; i < a.length; i++) {      // Iterate over numeric indexes from 0 to 5, as everyone expects.      console.log(a[i]);  }    /* Will display:     undefined     undefined     undefined     undefined     undefined     5  */

can sometimes be totally different from the other:

var a = [];  a[5] = 5;  for (var x in a) {      // Shows only the explicitly set index of "5", and ignores 0-4      console.log(x);  }    /* Will display:     5  */

Also consider that JavaScript libraries might do things like this, which will affect any array you create:

// Somewhere deep in your JavaScript library...  Array.prototype.foo = 1;    // Now you have no idea what the below code will do.  var a = [1, 2, 3, 4, 5];  for (var x in a){      // Now foo is a part of EVERY array and       // will show up here as a value of 'x'.      console.log(x);  }    /* Will display:     0     1     2     3     4     foo  */
like image 184
Kenan Banks Avatar answered Oct 11 '22 13:10

Kenan Banks