Categories
JavaScript Answers

How to loop through array backwards with forEach with JavaScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *