How can a for of
loop in es6 be made to start on the last item in the array and go down to the first instead of how it normally uses the variable++
behavior to iterate from first to last in the array's index.

- 1,031,962
- 187
- 1,923
- 1,875
-
`Array.reverse` - not ES6. – Mr_Green Nov 05 '15 at 08:01
2 Answers
The for..of
loop is one-directional, proceeding through the iterator's natural order. You can't change the direction of the iterator.
You could, of course, use a simple for
loop instead:
for (let i = theArray.length - 1; i >= 0; --i) {
let entry = theArray[i];
// ...
}
...but to use an interator for this (e.g., with for..of
), you have to change what it's iterating over, or the iterator it's using.
One way to do that is to reverse the order of the array first. Unfortunately, Array#reverse
modifies the array in place, and so if you want to keep the array in its original order, you have to clone it first (live example on Babel's REPL):
for (let entry of theArray.slice().reverse()) {
// ...
}
Another way is to write a reusable generator function that loops backward through an array:
function *backward(a) {
for (let i = a.length - 1; i >= 0; --i) {
yield a[i];
}
}
then:
let theArray = ["one", "two", "three"];
for (let entry of backward(theArray)) {
console.log(entry);
}
As RGraham points out, now that we can subclass arrays, you could even create an array subclass that provides backward
as its default iterator.
Gosh, so many options. :-)

- 1
- 1

- 1,031,962
- 187
- 1,923
- 1,875
-
simple `for` loop is the best way, this code is clear and easy to read – Andrew Evt Nov 05 '15 at 08:12
-
@AndrewEvt: Iterators are a powerful abstraction, that's why we have them. :-) But for just looping backward, yeah, hard to beat a simple `for` now we have block scoping. – T.J. Crowder Nov 05 '15 at 08:16
-
1Could also subclass Array and use your `backward` function as the default iterator. Not now, but in the future :) – CodingIntrigue Nov 05 '15 at 08:16
-
const array = [1,2,3,4,5];
for (let i = array.length; i--;) {
console.log(array[i]);
}
//5
//4
//3
//2
//1

- 40
- 4