It is known that a specific order of iteration is not guaranteed by the ECMA standard, but I'm not interested in the actual order of iteration. What I need to know is: do for-in loops at least guarantee the same order of iteration if executed more than once during the same session, provided obviously that no properties of the iterated object are added or removed between the subsequent for-in executions? I can guess there's no reason why this shouldn't happen, but I would like to find some reference.
-
1I can't say with any certainty myself, but barring the use of web-workers, I'd say there is probably some caching mechanism in inspecting the keys on a object. Seeing as that is 'single-threaded' (again, this is just high level thinking), if you were to call the same for..in loop immediately after the first round, you'd get the same set of keys in the order of the first. If for some reason you wanted to guarantee this, you could iterate over all keys, storing them in an array, then iterate of the array and access via `obj[crntKey]` – jusopi Aug 11 '15 at 18:33
-
See also http://stackoverflow.com/a/280861/560114 – Matt Browne Aug 11 '15 at 18:47
1 Answers
The order is arbitrary and you can only guess that it will always iterate in the same order. Just don't expect it to be always the same.
Quote below is for for-in used on arrays, the same applies for using it on object properties.
Because the order of iteration is implementation-dependent, iterating over an array may not visit elements in a consistent order.
The delete operator adds some extra info to that:
Although ECMAScript makes iteration order of objects implementation-dependent, it may appear that all major browsers support an iteration order based on the earliest added property coming first (at least for properties not on the prototype). However, in the case of Internet Explorer, when one uses delete on a property, some confusing behavior results, preventing other browsers from using simple objects like object literals as ordered associative arrays. In Explorer, while the property value is indeed set to undefined, if one later adds back a property with the same name, the property will be iterated in its old position--not at the end of the iteration sequence as one might expect after having deleted the property and then added it back.

- 27,376
- 9
- 90
- 133
-
From [this answer](http://stackoverflow.com/a/280861/560114): "In short: Use an array if order is important to you." If you loop an array using a regular `for` loop (as opposed to `for..in`, which should generally be avoided for arrays anyway) or a `forEach` callback, then of course the order will be consistent every time. – Matt Browne Aug 11 '15 at 18:47
-
Idd, what I was trying to say, it's not in the spec so one should never rely on it. – huysentruitw Aug 11 '15 at 18:49
-
Yes, I'm not disagreeing with your answer; I just think the link I provided gives some additional info that may be helpful. – Matt Browne Aug 11 '15 at 18:59