Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iteration order of for..in loops in Javascript

Tags:

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?

like image 281
Eli Courtwright Avatar asked Jun 10 '09 14:06

Eli Courtwright


People also ask

Does for of loop in order?

Yes. But hunting it down is a littlebit complicated, as for of doesn't only iterate arrays (like for in does enumerate objects). Instead, it generically iterates all iterable objects - in the order that their respective iterator supplies.

Which for loop is faster in JavaScript?

The fastest loop is a for loop, both with and without caching length delivering really similar performance.

How for in loop works in JavaScript?

for/in - loops through the properties of an object. for/of - loops through the values of an iterable object. while - loops through a block of code while a specified condition is true. do/while - also loops through a block of code while a specified condition is true.

Which is faster each or for loop?

The forloop is faster than the foreach loop if the array must only be accessed once per iteration.


4 Answers

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.

like image 64
Chadwick Avatar answered Oct 22 '22 04:10

Chadwick


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

like image 39
Keltex Avatar answered Oct 22 '22 04:10

Keltex


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.

like image 36
kennebec Avatar answered Oct 22 '22 04:10

kennebec


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

like image 31
Blixt Avatar answered Oct 22 '22 06:10

Blixt