The Array.reverse()
method is a built-in JavaScript function that reverses the order of elements in an array. It modifies the original array so that the first element becomes the last, the second element becomes the second-to-last, and so on.
Syntax
arr.reverse();
Parameters
The reverse()
method does not take any parameters.
Return Value
The reverse()
method returns the reversed array (the same array, now reversed). It also modifies the original array.
Example 1: Reversing a Simple Array
let arr = [10, 20, 30, 40, 50]; let revArr = arr.reverse(); console.log(revArr); // Output: [50, 40, 30, 20, 10] console.log(arr); // Output: [50, 40, 30, 20, 10]
Example 2: Reversing a String Array
let arr = ['HTML', 'CSS', 'JavaScript', 'jQuery']; let revArr = arr.reverse(); console.log(revArr); // Output: [ 'jQuery', 'JavaScript', 'CSS', 'HTML' ] console.log(arr); // Output: [ 'jQuery', 'JavaScript', 'CSS', 'HTML' ]
Example 3: Using reverse()
with Nested Arrays
let nestedArr = [[1, 2], [3, 4], [5, 6]]; let revArr = nestedArr.reverse(); console.log(revArr); // Output: [[5, 6], [3, 4], [1, 2]]
Example 4: Handling Sparse Arrays
let sparseArray = [10, , 30, , 50]; let revArr = sparseArray.reverse(); console.log(revArr); // Output: [ 50, <1 empty item>, 30, <1 empty item>, 10 ] console.log(sparseArray); // Output: [ 50, <1 empty item>, 30, <1 empty item>, 10 ]
Example 5: Reversing an Array Without Modifying the Original
To avoid modifying the original array, you can create a copy before reversing:
let arr = [10, 20, 30, 40, 50]; let revArr = [...arr].reverse(); console.log(revArr); // Output: [ 50, 40, 30, 20, 10 ] console.log(arr); // Output: [ 10, 20, 30, 40, 50 ]
Using the spread operator (...
) creates a shallow copy of the array, preserving the original.
Example 6: Combining with join()
to Reverse a String
let str = 'hello'; let revStr = str.split('').reverse().join(''); console.log(revStr); // Output: 'olleh'
Supported Browsers
Browser | Support |
---|---|
Chrome | 1+ |
Firefox | 1+ |
Safari | 1+ |
Edge | 12+ |
Opera | 4+ |
Internet Explorer | 5.5+ |