How to Reverse an Array in JavaScript

Reversing arrays and strings in JavaScript without surprises.

There are times when you need to flip the order of an array, like showing the newest comments first. JavaScript has a built-in reverse() method for this, but it comes with a catch that trips a lot of people up.

TL;DR arr.reverse() changes the original array. Use [...arr].reverse() to get a reversed copy instead.

.reverse()

The reverse() method reverses an array in place:

const numbers = [1, 2, 3, 4, 5]
numbers.reverse()
console.log(numbers) // [5, 4, 3, 2, 1]

In place means it mutates the original array. It also returns a reference to that same array, which makes it look like you got a new one:

const numbers = [1, 2, 3]
const reversed = numbers.reverse()
console.log(reversed) // [3, 2, 1]
console.log(numbers) // [3, 2, 1]
console.log(reversed === numbers) // true

This can lead to bugs that are hard to track down, for example when you reverse an array that came from React state or a prop and everything else using it flips too.

Copy First, Then Reverse

The fix is to make a copy and reverse the copy:

const numbers = [1, 2, 3]
const reversed = [...numbers].reverse()
console.log(numbers) // [1, 2, 3]
console.log(reversed) // [3, 2, 1]

The spread operator creates a new array, so reverse() only changes that one. numbers.slice().reverse() does the same thing if you prefer it.

Reversing a String

Strings don't have a reverse() method, but you can turn the string into an array, reverse it and join it back together:

const word = "hello"
const reversed = word.split("").reverse().join("")
console.log(reversed) // "olleh"

split("") splits the string into characters, reverse() flips them and join("") turns the array back into a string.

Note: split("") splits on UTF-16 code units, so characters like emojis that take up two code units get split in half and come out garbled. Using [...word] instead of word.split("") splits by code point and keeps them together.

Reversing with a Loop

If you need to do it by hand (this one comes up in interviews a lot), loop from the end of the array to the start:

function reverseArray(arr) {
const result = []
for (let i = arr.length - 1; i >= 0; i--) {
result.push(arr[i])
}
return result
}
reverseArray([1, 2, 3]) // [3, 2, 1]

The loop starts at the last index and pushes each item into a new array, so the original is never touched.

For everyday code, [...arr].reverse() is the cleanest option, since it leaves the original array alone.

Have some feedback on this post? .