Languages
[Edit]
EN

JavaScript - iterate array backwards

0 points
Created by:
trincot
360

In this article, we would like to show you how to iterate an array backwards in JavaScript.

1. Using for loop

Edit

In this example, we use a simple for loop to iterate the array from the last element (with index = array.length - 1) to the first one by decrementing the iterator (--i).

2. Using reverse() method with forEach()

Edit

In this example, we use slice() method to create a shallow copy of an array, then we use reverse() method to reverse the copy. Finally, we iterate the reversed copy of array using forEach().

Warning:

This is not a good solution because the array is copied first, then the copy is reversed and it is iterated at the end.

 

References

Edit
  1. for - JavaScript | MDN
  2. Array.prototype.slice() - JavaScript | MDN
  3. Array.prototype.reverse() - JavaScript | MDN
  4. Array.prototype.forEach() - JavaScript | MDN

Alternative titles

  1. JavaScript - loop through array backwards
1
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join