Vanilla JavaScript reverse an array

— 2 minute read

permalink

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 permalink

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.

See the Pen Vanilla JavaScript reverse an array by Chris Bongers (@rebelchris) on CodePen.

Thank you for reading, and let's connect! permalink

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter