Rodion Gorkovenko Rodion Gorkovenko - 1 year ago 95
Javascript Question

Does javascript array.forEach traverse elements in ascending order

In javascript I can have an array with holes:

a = [];
a[0] = 100;
a[5] = 200;
a[3] = 300;

a.forEach(function(x) {alert(x);});

I could not find information about whether elements would be processed in ascending order or this is not reliable fact.

I checked that "for .. in" loop traverses array indices in ascending order, while property names of an object are traversed in the same order they were added to object (at least it looks so).

(I.e. it looks like arrays are internally trees of some kind and objects are hashtables.)

I just found that Rhino JavaScript traverses non-existent elements also: (unlike

Answer Source

The ECMA-262, 5th edition specification and MDN's Array.forEach() page both show the algorithm for .forEach(), and it will definitely iterate over array elements in ascending index order (skipping indices that were never assigned a value).

Of course, some browsers may not implement that algorithm properly, but I'm not aware of any that don't.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download