Reversing Arrays in JavaScript

I have been a full-stack developer for twelve years and am currently part of the Cloud FinOps team at Atlassian. I previously ran an App development agency, managing various teams across design and development, leading web, backend and native mobile app developers in Australia and Europe. My strengths are system architecture design and communicating complicated tech to everyday people. Having helped scale tech at numerous startups, I am passionate about making a positive difference. When not working, you can find me writing tech articles and teaching Javascript and React at SheCodes, an initiative helping to get more women into tech. I regularly give talks on various topics, focusing on the impact the technology we build can have. I am devastated by the state of the world, love a good political rant and can often be swearing at no one in particular. I enjoy building things in JavaScript, Deno and Node.
JavaScript has two built-in functions for reversing arrays. The first method is Array.prototype.reverse() which reverses the array in place, meaning we change the original array.
const numbers = [5, 10, 15, 20, 25, 30]
const reversed = numbers.reverse()
console.log(reversed) // 30, 25, 20, 15, 10, 5
console.log(numbers) // 30, 25, 20, 15, 10, 5
Looking at the code, you can see that the reverse function returns a reference to the original array, which has now been reversed. However, what if we don't want to mutate the original array? Well, we got a newer function for that.
const numbers = [5, 10, 15, 20, 25, 30]
const reversed = numbers.toReversed()
console.log(reversed) // 30, 25, 20, 15, 10, 5
console.log(numbers) // 5, 10, 15, 20, 25, 30
As you can see Array.prototype.toReversed() returns a new array and does not touch the original. Both these functions also iterate over empty slots as if they have the value undefined, keeping those empty slots in place.
As of the time of writing this post, both functions are supported in all major browsers, so give them a try next time you need to reverse an array.
You can find the full browser support breakdown for these functions here:




