3

I have been reading Object-Oriented Javascript by Stoyan Stefanov, and at one point he writes:

The for-in loop is used to iterate over the element of an array (or an object, as we'll see later). This is it's only use; it can not be used as a general-purpose repetition mechanism that replaces for or while. Let's see an example of using a for-in to loop through the elements of an array. But bear in mind that this is for informational purposes only, as for-in is mostly suitable for objects, and the regular for loop should be used for arrrays.

I have always used for loops in the past when iterating of the elements of an array and I have usually seen for loops not for-in loops used for this purpose, but what is the reason that the "regular for loop should be used for arrays"?

James
  • 933
  • 1
  • 7
  • 14
  • possible duplicate of [JavaScript "For ...in" with Arrays](http://stackoverflow.com/questions/500504/javascript-for-in-with-arrays) – Bergi Jun 19 '12 at 21:48

3 Answers3

3

The reason to use regular for loops for arrays is that it limits the iteration to indexed values.

If you use a for-in loop, it will iterate through all properties on the object (an array is an object), and may give you unexpected results if you attach arbitrary properties to an array that aren't numerically indexed.

Peter
  • 6,354
  • 1
  • 31
  • 29
1

The issue is that some libraries (Prototype comes to mind) extend the array type, so when you use a for in loops, it hits all of the enumerable properties on that array, which includes all elements of the array, but also all added on properties or methods. Not what you want to have happen.

The for i in loop iterates only over the elements of the array, that is, anything you'd define literally as [1, 2, 3, 4].

Alex Mcp
  • 19,037
  • 12
  • 60
  • 93
0

Well i mostly use it when i dont know the exact number of elements in an array. in general it is used for iterating on elements when the array is dynamically or on the fly populated.

samach
  • 3,244
  • 10
  • 42
  • 54
  • 1
    This doesn't make sense because the array length is always available with x.length. My array loops look like this: for (var i=0,len=x.length;i – jfriend00 Jul 09 '11 at 20:40