In this tutorial, you are going to learn about the javascript array reverse method with the help of multiple examples.
The array reverse()
method in javascript is used to reverse the order of the elements in an array. Instead of returning a new array with reversed elements, it reverses the elements of the original array.
Example
let arr = [1, 2, 3, 4, 5];
//reverse the original array
arr.reverse();
console.log(arr);
// Output: [ 5, 4, 3, 2, 1 ]
Also Read:
Array reverse() Syntax
arr.reverse()
Here arr
is an array.
Array reverse() Parameters
The reverse()
method doesn’t take any parameters.
Array reverse() Return Value
It doesn’t provide any copy of reversed array elements instead, it reverses the original array elements.
Example 1: Using the Array reverse() Method
let numbers = ["one", "two", "three", "four", "five"];
//reverse the original array
let reversed = numbers.reverse();
console.log(reversed);
// Output: [ 'five', 'four', 'three', 'two', 'one' ]
console.log(numbers);
// Output: [ 'five', 'four', 'three', 'two', 'one' ]
Output
[ 'five', 'four', 'three', 'two', 'one' ]
[ 'five', 'four', 'three', 'two', 'one' ]
In the above example, we reversed the order of elements of the numbers
array with the help of the reverse()
method.
You can notice in the above program that reversed
and numbers
return the same reversed array, this is because the reverse()
method modifies the original array.
Example 2: Using the Array reverse() Method with spread Operator
As we know that the reverse()
method modifies the original array, what if we don’t want to modify the original array but instead we want the reverse()
method to return a new array?
So to solve this problem we have spread operator(...)
, With the help of the spread operator, we can apply the reverse method on the copy of the original array.
let numbers = ["one", "two", "three", "four", "five"];
let reversed = [...numbers].reverse();
console.log(reversed);
// Output: [ 'five', 'four', 'three', 'two', 'one' ]
console.log(numbers);
// Output: [ 'one', 'two', 'three', 'four', 'five' ]
Output
[ 'five', 'four', 'three', 'two', 'one' ]
[ 'one', 'two', 'three', 'four', 'five' ]
In the above program, we have taken a copy of the numbers array using the spread operator [...numbers]
. So instead of reversing the elements of the original array, we are reversing the elements of its copy.