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.
array.reverse()
The reverse()
function in JavaScript takes no input parameters.
The returned value is an array that represents the original array after it has been reversed.
In the example below, we will create some arrays and use the reverse()
method on them.
// creating arrayslet 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 consoleconsole.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 arraylet array = [1, 2, 3, 4, 5];console.log("Original array: ", array);// reverse the original arraylet revArray = array.reverse();// log reversed arrayconsole.log("Reversed array: ", revArray); // [5, 4, 3, 2, 1]// logout original array, but has changedconsole.log("Original array: ", array) // [5, 4, 3, 2, 1]