Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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: http://ideone.com/7Z3AFh (unlike for..in).

like image 630
Rodion Gorkovenko Avatar asked Nov 28 '12 08:11

Rodion Gorkovenko


2 Answers

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.

like image 66
nnnnnn Avatar answered Sep 21 '22 00:09

nnnnnn


The specification says forEach will visit the array elements in numeric order. It doesn't visit elements that don't exist. See the link for details. So for your example array, it will visit element 0, then 3, then 5. The order in which you add them to the array has no effect on the order in which they're visited.

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).

The order in which for-in visits object properties is not defined by the specification, not even in ES2015 (aka ES6), despite the fact that ES2015 defines an order for object properties — that order doesn't apply to for-in or Object.keys. (More about that in this answer.) If you want to visit properties in the order defined in ES2015, you can use Object.getOwnPropertyNames (for properties that aren't defined with Symbol names) or Reflect.ownKeys (for both Symbol and string property names [remember numeric property names are really strings]). Both of those do respect property order.

like image 20
T.J. Crowder Avatar answered Sep 23 '22 00:09

T.J. Crowder