Reverse an Array in JavaScript (original) (raw)

Last Updated : 20 Jan, 2025

Try it on GfG Practice redirect icon

Here are the different methods to reverse an array in JavaScript

1. Using the reverse() Method

JavaScript 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);

`

2. Using For Loop

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);

`

3. Using Recursion

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);

`

4. Using the reduce() Method

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);

`

5. Using the Spread Operator and reverse()

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);

`

6. Using a Stack (Last-In-First-Out Approach)

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);

`

Similar Reads

Mathematical









Recursion







Array








Searching






Sorting












Hashing



String







Linked List