How to Reverse an Array in JavaScript and Node.js

When working with arrays in JavaScript you may need to reverse it. Reversing the array will make the last item the first one, the second to last item the second one, and so on. This tutorial shows how to reverse an array in JavaScript and what side effects to keep in mind.

Node.js Series Overview

Reverse an Array and Mutate the Original

JavaScript provides a reverse method for arrays. You can directly chain the array.reverse() method and retrieve the reversed array. Be careful here: the reverse method changes the original array:

const numbers = [1, 2, 3]

numbers.reverse()

console.log(numbers)  
// [3, 2, 1]

Reverse an Array Without Changing the Original

When reversing an array in JavaScript you may want to keep the original array “as is”. You can copy an existing array using the spread operator, the concat or slice methods. All three approaches keep the order in the original array and only mutate the copy:

const numbers = [1, 2, 3]

const reversed = [].concat(numbers).reverse()  
// or
const reversed = numbers.slice().reverse()  
// or
const reversed = [...numbers].reverse()  

We typically use the spread operator ([...numbers]) to create a copy of a given array. It’s a common approach in the team because we know what the spread operator does and why we’re spreading an array into another.

That’s it! Enjoy reversing arrays!

Explore the Library

Find interesting tutorials and solutions for your problems.