Vanilla JavaScript reverse an array

Vanilla JavaScript reverse an array

Β·

2 min read

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

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

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

Did you find this article valuable?

Support Chris Bongers by becoming a sponsor. Any amount is appreciated!