## DEV Community is a community of 901,364 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

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()
``````

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]
``````

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]
``````

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]
``````

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

## Discussion (2)

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), [])
``````
Dillion Megida

this took me some time to understand haha