Last Updated : 20 Jan, 2025
Try it on GfG Practice
Here are the different methods to reverse an array in JavaScript
1. Using the reverse() MethodJavaScript provides a built-in array method called reverse() that reverses the elements of the array in place. This method mutates the original array and returns the reversed array.
JavaScript
let a = [1, 2, 3, 4, 5];
a.reverse();
console.log(a);
Another approach is to manually reverse an array by using a loop to swap elements.
JavaScript
const a = [1, 2, 3, 4, 5];
for (let i = 0; i < Math.floor(a.length / 2); i++) {
let temp = a[i];
a[i] = a[a.length - 1 - i];
a[a.length - 1 - i] = temp;
}
console.log(a);
You can use recursion by removing the first element of the array, reversing the rest of the array, and then pushing the removed element to the end of the reversed array.
JavaScript
const a = [1, 2, 3, 4, 5];
const reversed = (function reverse(a) {
if (a.length === 0) {
return [];
}
return [a.pop()].concat(reverse(a));
})([...a]);
console.log(reversed);
The reduce() method can be used to accumulate the elements of the array in reverse order by pushing each element to the front of the accumulator.
JavaScript
let a = [1, 2, 3, 4, 5];
let revArr = a.reduce((acc, current) =>
[current, ...acc], []);
console.log(revArr);
You can use the spread operator (...) to create a shallow copy of the array and then apply the reverse() method on that copy.
JavaScript
let a = [1, 2, 3, 4, 5];
let reversed = [...a].reverse();
console.log(reversed);
A stack follows the Last-In-First-Out (LIFO) principle, which can be used to reverse an array by pushing elements to the stack and then popping them back out.
JavaScript
const a = [1, 2, 3, 4, 5];
const rev = [];
while (a.length > 0) {
rev.push(a.pop());
}
console.log(rev);
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4