How to Reverse an Array in JavaScript
Array.reverse()
In this tutorial, we’ll learn how to reverse an Array in JavaScript using Array.reverse()
method.
Array.reverse()
The easiest way to reverse an array is to use reverse()
method.
const list = [1, 2, 3, 4, 5];
list.reverse();
console.log(list);
// prints [5, 4, 3, 2, 1]
Here is the catch, it reversed the elements of your original array. Sometime you wish not to alter the original array, and assign it to a new variable instead.
You can do in two steps:
- First you have to make a copy of the original array
- Reverse the copy and assign it to a new variable
In Javascript, you can do this in multiple ways in a single statement.
Spread Operator (…) and Array.reverse()
It is recommended to use spread operator ...
to make a copy of an array and chain it with reverse()
method. It’s short syntax is very handy.
const list = [1, 2, 3, 4, 5];
const reversedList = [...list].reverse();
console.log(list);
// prints [1, 2, 3, 4, 5]
console.log(reversedList);
// prints [5, 4, 3, 2, 1]
We see that our original array remains the same and reversed array is assigned to a new variable.
Array.slice() and Array.reverse()
You can also chain slice()
method with reverse()
method to make a new copy of reversed array.
const list = [1, 2, 3, 4, 5];
const reversedList = list.slice().reverse();
console.log(list);
// prints [1, 2, 3, 4, 5]
console.log(reversedList);
// prints [5, 4, 3, 2, 1]
Array.from() and Array.reverse()
Another way is to chain Array.from()
method with reverse()
method to make a new copy of reversed array.
const list = [1, 2, 3, 4, 5];
const reversedList = Array.from(list).reverse();
console.log(list);
// prints [1, 2, 3, 4, 5]
console.log(reversedList);
// prints [5, 4, 3, 2, 1]