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: