DEV Community

Cover image for Vanilla JavaScript reverse an array
Chris Bongers
Chris Bongers

Posted on • Originally published at daily-dev-tips.com

Vanilla JavaScript reverse an array

You will often want to reverse an array in JavaScript, imagine you're receiving data based on a date, but you want it to show it reversed in the frontend.

This is where the JavaScript reverse method comes in handy.
It's a super cool array method, and it's easy to use.

To reverse an array, we can call the reverse method on a variable.

const array = ['a', 'b', 'c'];
array.reverse();
// [ 'c', 'b', 'a' ]
Enter fullscreen mode Exit fullscreen mode

As you can see, this 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 the JavaScript spread operator comes in handy.

const array = ['a', 'b', 'c'];
const reverse = [...array].reverse();
// array: [ 'a', 'b', 'c' ]
// reverse: [ 'c', 'b', 'a' ]
Enter fullscreen mode Exit fullscreen mode

And that's it, reversing arrays is pretty straightforward and comes in super handy.

You can have a play with today's code in the following 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

Top comments (0)