To loop through array backwards with forEach with JavaScript, we call reverse
before calling forEach
.
For instance, we write
const arr = [1, 2, 3];
arr
.slice()
.reverse()
.forEach((x) => console.log(x));
to call arr.slice
to return a copied version of the arr
array.
And then we call reverse
to reverse the copied array.
Then we call forEach
with a callback to log each entry x
being looped through.