The reverse() method in JavaScript is used to reverse the elements of an array. It modifies the array in place and returns the reversed array.
Syntax
array.reverse();
Return Value
Return Type | Description |
---|---|
Array | The reversed array. |
Example 1: Reversing an Array
This code demonstrates how to use the reverse() method to reverse the elements of an array.
let Arr = [ 10, 20, 30, 40, 50 ]; Arr.reverse(); console.log(Arr);
Output:
[ 50, 40, 30, 20, 10 ]
Example 2: Reversing String Array
The reverse()
method can also be used to reverse a string array.
let Arr = ['Apple', 'Banana', 'Orange', 'Mango']; Arr.reverse(); console.log(Arr);
Output:
[ 'Mango', 'Orange', 'Banana', 'Apple' ]
Example 3: Reversing Mixed Array
You can also reverse an array containing different data types.
let mixedArray = [1, 'Hello', true, { name: 'John' }]; mixedArray.reverse(); console.log(mixedArray);
Output:
[ { name: 'John' }, true, 'Hello', 1 ]
Note:
The reverse() method changes the original array and does not create a new array. If you need to preserve the original array, you should create a copy of it before calling reverse().
Supported Browsers
Chrome | Edge | Firefox | Opera | Safari |
---|---|---|---|---|
1 | 12 | 1 | 4 | 1 |