JavaScript reverse() Method
This tutorial explains the reverse() method from JavaScript's Array object. The reverse() method inverts the current order of array elements, but without sorting them in any way during the process.
Related array method:
The sort() method sorts array elements alpha-numerically (by default), in ascending order.
On the other hand, the reverse() method does not sort array elements: it only inverts their current order.
Using the reverse() Method
The script below demonstrates how the reverse() method works. To emphasize the fact that reverse() does not perform any kind of sort, we did not list the array elements alphabetically.
// Notice that array elements are not sorted alphabetically
var arlene = new Array("alpha", "gamma", "beta");
alert( arlene.reverse() );
The reverse() method returns a copy of the original array with elements' order reversed. But reverse() also modifies the array on which it is called.
The reverse() method inverted the order of array elements (no sorting).
The reverse() method can be nested. As example, the code below has no effect on the original order of array elements: Array.reverse().reverse()
Test the reverse() Method
Interactively test the reverse() method by editing the JavaScript code below and clicking the Test reverse() Method button.
Browser support for JavaScript reverse() method | |||
---|---|---|---|