You will often need to reverse an array in JavaScript.
Imagine you’re receiving data based on a date, for example. In the frontend, you’ll most likely want to show the data reversed, meaning the most recent date first.
This is where the JavaScript reverse method comes in handy.
It’s a super cool array method, and it’s easy to use.
To do an array reverse in JavaScript, call the reverse method on a variable, like this:
const array = ['a', 'b', 'c'];
array.reverse();
// [ 'c', 'b', 'a' ]
As you can see, the method reversed our initial input array.
JavaScript reverse array but keep original
You might not want to reverse the original array in some cases but want to create a copy.
This is where we can use the JavaScript spread operator.
const array = ['a', 'b', 'c'];
const reverse = [...array].reverse();
// array: [ 'a', 'b', 'c' ]
// reverse: [ 'c', 'b', 'a' ]
And that is how to reverse an array in JavaScript. You learn two methods: One changes the original array and the other creates a new array in reversed order.
Reversing arrays is pretty straightforward and comes in super handy.
See the example code in this Codepen
You can have a play with today’s code here:
See the Pen Vanilla JavaScript reverse an array by Chris Bongers (@rebelchris) on CodePen.
Thank you for reading, and let’s connect!
Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter