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.
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...inwill return the indexes in any particular order. The
for...inloop 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
reduce, and so on.