Eli Courtwright
Eli Courtwright

Reputation: 192921

Iteration order of for..in loops in Javascript

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?

Upvotes: 18

Views: 7197

Answers (5)

Keltex
Keltex

Reputation: 26426

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

Upvotes: 4

kennebec
kennebec

Reputation: 104770

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.

Upvotes: 2

Chadwick
Chadwick

Reputation: 12663

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.

Upvotes: 13

Blixt
Blixt

Reputation: 50169

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

Upvotes: 1

Alsciende
Alsciende

Reputation: 26971

No, you should not rely on this.

Upvotes: 0

Related Questions