DEV Community

Cover image for Array.reverse() - for reversing an array
Dillion Megida
Dillion Megida

Posted on

Array.reverse() - for reversing an array

This article is the ninth of the Array Method Series. In this article, I will explain the reverse Array method.

What is the Reverse Method?

I think the name says it all 😅. The reverse method of arrays reverses the array such that the last item in the array becomes the first, and the first item becomes the last.

This method modifies the array, so I recommend cloning before reversing to avoid mutation conflicts in your applications.

Syntax of the Reverse Method

array.reverse()
Enter fullscreen mode Exit fullscreen mode

While this method mutates the array, it also returns the reversed array.

Without the Reverse Method

The reverse method is an abstracted function that flips the array from one side to the other. Here's an example imitating the reverse method:

const array = [1, 2, 3, 4, 5, 6, 7, 8]

const reversed = []

for (let i = array.length - 1; i > -1; i--) {
  const item = array[i]
  reversed.push(item)
}

console.log(reversed)
// [8, 7, 6, 5, 4, 3, 2, 1]
Enter fullscreen mode Exit fullscreen mode

This loops through each item in the array from the back to the front. Although this loop does not mutate the original array, it is similar to what reverse does in the background.

With the Reverse Method

Here's how you achieve the previous result with reverse:

const array = [1, 2, 3, 4, 5, 6, 7, 8]

const reversed = array.reverse()

console.log(reversed)
// [8, 7, 6, 5, 4, 3, 2, 1]

console.log(array)
// initial array is also modified
// [8, 7, 6, 5, 4, 3, 2, 1]
Enter fullscreen mode Exit fullscreen mode

As you can see, the initial array is also modified. So to avoid mutation conflicts, you can clone the array like this:

const array = [1, 2, 3, 4, 5, 6, 7, 8]

const reversed = [...array].reverse()

console.log(reversed)
// [8, 7, 6, 5, 4, 3, 2, 1]

console.log(array)
// [1, 2, 3, 4, 5, 6, 7, 8]
Enter fullscreen mode Exit fullscreen mode

With this, the initial array stays the same, and you can get the reversed array also.

Top comments (2)

Collapse
 
jonrandy profile image
Jon Randy 🎖️

Some other (non-mutating) alternatives with reduce:

const reverse = arr => arr.reduce((r, i) => [i, ...r], [])
const reverse2 = arr => arr.reduce((r, i) => (r.unshift(i), r), [])
Enter fullscreen mode Exit fullscreen mode
Collapse
 
dillionmegida profile image
Dillion Megida

this took me some time to understand haha