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.

asked Sep 17, 2018 at 1:29
5
  • 3
    Possible duplicate of Elements order in a "for (... in ...)" loop Commented Sep 17, 2018 at 1:30
  • 1
    @Thornkey, there's a for...of loop you can use for arrays (and other iterables) Commented Sep 17, 2018 at 1:35
  • ik, doesnt seem to work in all browsers though ;-; Commented Sep 17, 2018 at 1:42
  • @Trent yeah i was just wondering about arrays specifically :) Commented Sep 17, 2018 at 1:42
  • 1
    Related: stackoverflow.com/questions/30076219/… Commented Sep 17, 2018 at 1:43

1 Answer 1

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.

answered Sep 17, 2018 at 1:31
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.