Array.reverse()
The Array.reverse()
method in JavaScript reverses the order of the elements in an array in place. The first array element becomes the last, and the last becomes the first. This method modifies the original array and also returns it.
Syntax
array.reverse()
Parameters
The reverse()
method does not take any parameters.
Return Value
The reverse()
method returns the reversed array. It also modifies the original array in place, meaning the original array is changed.
Examples
1. Reversing an Array
This example demonstrates how to reverse the elements of an array.
const array = [1, 2, 3, 4, 5];
array.reverse();
console.log(array);
Output
[5, 4, 3, 2, 1]
- The original array is modified, and its elements are reversed.
reverse()
returns the reversed array.
2. Reversing a String Array
The method works for arrays of any type, including strings.
const fruits = ["apple", "banana", "cherry"];
fruits.reverse();
console.log(fruits);
Output
[ 'cherry', 'banana', 'apple' ]
The order of the fruit names in the array is reversed.
3. Using reverse()
with Chaining
You can chain the reverse()
method with other array methods.
const numbers = [1, 2, 3, 4, 5];
const reversed = numbers.reverse().join(", ");
console.log(reversed);
Output
5, 4, 3, 2, 1
- The
reverse()
method reverses the array in place. - The
join()
method converts the reversed array into a string.
4. Avoiding Side Effects of reverse()
Since reverse()
modifies the original array, create a copy to avoid side effects.
const array = [1, 2, 3, 4, 5];
const reversedCopy = [...array].reverse();
console.log(array);
console.log(reversedCopy);
Output
[1, 2, 3, 4, 5]
[5, 4, 3, 2, 1]
The original array remains unmodified because a copy is created using the spread operator ([...array]
).