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?
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.
The fastest loop is a for loop, both with and without caching length delivering really similar performance.
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.
The forloop is faster than the foreach loop if the array must only be accessed once per iteration.
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.
The order is not guaranteed. See this SO question for more information: Iterate over a Javascript associative array in sorted order.
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.
The order is defined in specifications as "arbitrary", so no; you shouldn't rely on the order being definite.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With