Iterating over an array using for...in
doesn't guarantee order, however ES6 introduces a new construct for...of
.
My limited testing of implementations of for...of
indicates that it does iterate in order on array, but is this property guaranteed?
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.
JavaScript arrays are an ordered collection that can hold data of any type.
The for ... in syntax mentioned by others is for looping over an object's properties; since an Array in JavaScript is just an object with numeric property names (and an automatically-updated length property), you can theoretically loop over an Array with it.
Using for (var property in array) will cause array to be iterated over as an object, traversing the object prototype chain and ultimately performing slower than an index-based for loop. for (... in ...) is not guaranteed to return the object properties in sequential order, as one might expect.
There are multiple ways one can iterate over an array in Javascript. The most useful ones are mentioned below. Using for loop. Using while loop. This is again similar to other languages. using forEach method. The forEach method calls the provided function once for every array element in the order.
The for...of Loop iterates over iterable objects such as arrays, sets, maps, strings, and so on. It has the same syntax as the for...in loop, but instead of getting the key, it gets the element itself. This is one of the easiest methods for looping through an array and was introduced in later versions of JavaScript ES6.
The JavaScript for/of statement loops through the values of an iterable object. It lets you loop over iterable data structures such as Arrays, Strings, Maps, NodeLists, and more: variable - For every iteration the value of the next property is assigned to the variable. Variable can be declared with const, let, or var.
This chapter of the JavaScript Guide introduces the different iteration statements available to JavaScript. You can think of a loop as a computerized version of the game where you tell someone to take X steps in one direction, then Y steps in another.
Iterating over an array using
for...in
doesn't guarantee order, however ES6 introduces a new constructfor...of
.My limited testing of implementations of
for...of
indicates that it does iterate in order on array, but is this property guaranteed?
Yes, the order of for-of
on arrays is guaranteed by the array iterator definition: It will visit the entries in the array in numeric index order (including ones that don't exist, such as those in sparse arrays — or perhaps that should be those not in sparse arrays :-) ):
Live Example on Babel's REPL, and here's an on-site snippet for those using an up-to-date browser:
"use strict";
let a = [];
a[3] = 'd';
a[0] = 'a';
a.foo = "f";
for (let v of a) {
console.log(v);
}
Output:
a undefined undefined d
(The two undefined
s show as blank in Babel's REPL.)
Two things to note above:
Even though the array has an enumerable property foo
, it isn't visited.
The array is sparse, and for-of
did visit the two entries that aren't present (at indexes 1 and 2).
for-in
, however, does not did not have a guaranteed order in ES2015 (aka "ES6") through ES2019; in ES2020, it follows the same property order (with some caveats) as the order-obeying mechanisms added in ES2015 (Object.getOwnPropertyNames
, etc.). Consider this example:
"use strict";
var a = [];
a.foo = "f";
a[3] = 'd';
a[0] = 'a';
a.bar = "b";
var key;
for (key in a) {
console.log(key);
}
In ES2015 through ES2019, it might output
0 3 foo bar
or
foo bar 0 3
or something else. As of ES2020, though, it is specified to output
0 3 foo bar
because it has to visit the integer index properties first (properties whose names are strings in standard numeric form) in numeric order, followed by other properties in creation order (so, foo
before bar
).
(That assumes there are no enumerable properties on Array.prototype
or Object.prototype
(by default there aren't). If there were, we'd see them as well, but it's not specified where.)
If you want to loop through an array's values, for-of
is a great tool as of ES2015, alongside the other useful tools such as Array#forEach
(forEach
is particularly handy on sparse arrays; it skips the entries that don't exist). for-in
is rarely a good choice. There's an exhaustive list of options in this other answer.
My limited testing of implementations of
for...of
indicate it does iterate in order on array, but is this property guaranteed?
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.
In fact arrays are such an iterable, and when getting an iterator from them it will be an iterator that yields all elements of the array in the same order as they can be found in the array. You can read the spec for ArrayIterator
objects, they basically work like a for (var index=0; index<array.length; index++) yield array[index];
loop.
As per ES6 spec for for..of
for ( LeftHandSideExpression of AssignmentExpression ) Statement
If LeftHandSideExpression is either an ObjectLiteral or an ArrayLiteral and if the lexical token sequence matched by LeftHandSideExpression can be parsed with no tokens left over using AssignmentPattern as the goal symbol then the following rules are not applied. Instead, the Early Error rules for AssignmentPattern are used.
As per this grammar rule definition a for..of loop will be executed in the lexical order of the tokens when it is an Array or Object Literal.
Here is a nice blog link by David Walsh http://davidwalsh.name/es6-generators where he has explained with example how a for..of
loop works using iterators.
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