Reversing a JavaScript array can be done using a few different methods. In this article, we will explore the different ways to achieve this.
Let’s start with an example array called list:
const list = [1, 2, 3, 4, 5];
The easiest and most intuitive way to reverse an array is by using the built-in reverse() method. This method directly alters the original array, so you can call it directly on list:
const list = [1, 2, 3, 4, 5];
list.reverse();
// Output: list is [5, 4, 3, 2, 1]
If you want to keep the original array intact and create a new reversed array, you can use the spread operator ... along with the reverse() method:
const list = [1, 2, 3, 4, 5];
const reversedList = [...list].reverse();
// Output: list is [1, 2, 3, 4, 5]
// Output: reversedList is [5, 4, 3, 2, 1]
Another approach is to use the slice() method without passing any arguments. This creates a shallow copy of the original array, and then you can call the reverse() method on the copied array:
const list = [1, 2, 3, 4, 5];
const reversedList = list.slice().reverse();
// Output: list is [1, 2, 3, 4, 5]
// Output: reversedList is [5, 4, 3, 2, 1]
Personally, I find the spread operator approach more intuitive than using slice().
With these methods, you can easily reverse a JavaScript array and manipulate it to suit your needs.