0

I know that using for...in is meant to be for objects, and I also know that for i=0;i<arr.length;i++ loops work fine, but sometimes I want to use for..ins for looping through arrays (I code in both python and js, but my poor brain doesn't want to constantly change my coding style.)

My question is: Is it guarunteed that using for...in will give me array objects in order?

PS. My question is specifically for ARRAYS, instead of objects with potential ambiguity in order, so I thought it might be different.

Thornkey
  • 694
  • 7
  • 18

1 Answers1

1

No, property order is not guaranteed, even with array indicies. As MDN says:

Array indexes are just enumerable properties with integer names and are otherwise identical to general object properties. There is no guarantee that for...in will return the indexes in any particular order. The for...in loop statement will return all enumerable properties, including those with non–integer names and those that are inherited.

I don't think there are many situations to use for..in. If you're working with an array, better to use array methods like forEach, map, reduce, and so on.

CertainPerformance
  • 260,466
  • 31
  • 181
  • 209