How to reverse an array in JavaScript

In JavaScript, reversing an array can be done using a built-in array method known as reverse(). The reverse() method is used to reverse an array, returning the same array but in a reversed form.

Syntax

array.reverse()

Parameters

The reverse() function in JavaScript takes no input parameters.

Return value

The returned value is an array that represents the original array after it has been reversed.

Code

In the example below, we will create some arrays and use the reverse() method on them.

// creating arrays
let array1 = [1, 2, 3, 4, 5]
let array2 = ["a", "b", "c", "d", "e"]
let array3 = ["Javascript", "Python", "Java", "C++", "Ruby"]
// logging the reversed methods to the console
console.log(array1.reverse())
console.log(array2.reverse())
console.log(array3.reverse())

The reverse() method overwrites the original array.

In some programming languages, reversing an array may not overwrite the array. But reverse() in JavaScript overwrites the original array.

// create an array
let array = [1, 2, 3, 4, 5];
console.log("Original array: ", array);
// reverse the original array
let revArray = array.reverse();
// log reversed array
console.log("Reversed array: ", revArray); // [5, 4, 3, 2, 1]
// logout original array, but has changed
console.log("Original array: ", array) // [5, 4, 3, 2, 1]