18

Suppose I have a Javascript object which is initialized

var letters = {q:0, t:0, o:0, b:0, y:0, n:0, u:0, m:0, p:0, 
               w:0, a:0, d:0, k:0, v:0, c:0, z:0, l:0, j:0, 
               i:0, e:0, g:0, s:0, x:0, r:0, h:0, f:0};

and then I want to iterate over the keys of this objects

for(var letter in letters) {
    // code goes here
}

In both Firefox 3 and Internet Explorer 8 the objects are iterated over in the order in which they are listed in the object declaration (q, t, o, b, y, etc).

Can I rely on this? Assume that I don't modify my object in any way before the iteration. Is it part of the ECMAScript standard? Does anyone know which browsers iterate in the declared order?

Eli Courtwright
  • 186,300
  • 67
  • 213
  • 256
  • 3
    Dup: http://stackoverflow.com/questions/919027/are-object-variables-in-javascript-enumerated-in-the-order-they-were-added and http://stackoverflow.com/questions/280713/elements-order-for-in-loop-in-javascript – Crescent Fresh Jun 10 '09 at 15:17

5 Answers5

13

No, it cannot be relied upon, at least not in Firefox:

A for...in loop iterates over the properties of an object in an arbitrary order.

Chadwick
  • 12,555
  • 7
  • 49
  • 66
  • 2
    Actually, in Firefox you can depend on this, but not in Chrome; see http://stackoverflow.com/questions/280713/elements-order-for-in-loop-in-javascript – doekman Apr 15 '11 at 10:31
  • 4
    You should not depend on a reproducible order in any browser. The order is given by the current implementation but may change at any time. The linked doc by Mozilla does explicitly call the order arbitrary. – Augustus Kling Mar 11 '13 at 13:50
4

The order is not guaranteed. See this SO question for more information: Iterate over a Javascript associative array in sorted order.

Community
  • 1
  • 1
Keltex
  • 26,220
  • 11
  • 79
  • 111
2

To ensure a particular order for processing an object's properties in a for-in loop, you'll need to define a sort order or list method for the object. If you define all the properties when you create the object, an array of property names will do, but if you can add or remove properties, a method is required.

If the processing order is essential for some reason, an array may be preferable.

kennebec
  • 102,654
  • 32
  • 106
  • 127
1

The order is defined in specifications as "arbitrary", so no; you shouldn't rely on the order being definite.

Blixt
  • 49,547
  • 13
  • 120
  • 153
0

No, you should not rely on this.

Alsciende
  • 26,583
  • 9
  • 51
  • 67