Does javascript "for x in array" garuntee order?

2583 views javascript
1

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.

answered question

@Thornkey, there's a for...of loop you can use for arrays (and other iterables)

ik, doesnt seem to work in all browsers though ;-;

@Trent yeah i was just wondering about arrays specifically :)

1 Answer

8

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.

posted this

Have an answer?

JD

Please login first before posting an answer.