Array.prototype.reverse()
The reverse()
method reverses an array in place. The first
array element becomes the last, and the last array element becomes the first.
Syntax
reverse()
Return value
The reversed array.
Description
The reverse
method transposes the elements of the calling array object in
place, mutating the array, and returning a reference to the array.
reverse
is intentionally generic; this method can be
called or applied to objects resembling arrays. Objects which do not contain a
length
property reflecting the last in a series of consecutive, zero-based
numerical properties may not behave in any meaningful manner.
Examples
Reversing the elements in an array
The following example creates an array items
, containing three elements, then
reverses the array. The call to reverse()
returns a reference to the
reversed array items
.
const items = [1, 2, 3];
console.log(items); // [1, 2, 3]
items.reverse();
console.log(items); // [3, 2, 1]
Reversing the elements in an array-like object
The following example creates an array-like object obj
, containing three
elements and a length property, then reverses the array-like object. The call to
reverse()
returns a reference to the reversed array-like object
obj
.
const obj = {0: 1, 1: 2, 2: 3, length: 3};
console.log(obj); // {0: 1, 1: 2, 2: 3, length: 3}
Array.prototype.reverse.call(obj); //same syntax for using apply()
console.log(obj); // {0: 3, 1: 2, 2: 1, length: 3}
Specifications
Specification |
---|
ECMAScript Language Specification # sec-array.prototype.reverse |
Browser compatibility
Report problems with this compatibility data on GitHubdesktop | mobile | server | ||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
reverse | ChromeFull support1 | EdgeFull support12 | FirefoxFull support1 | Internet ExplorerFull support5.5 | OperaFull support4 | SafariFull support1 | WebView AndroidFull support1 | Chrome AndroidFull support18 | Firefox for AndroidFull support4 | Opera AndroidFull support10.1 | Safari on iOSFull support1 | Samsung InternetFull support1.0 | DenoFull support1.0 | Node.jsFull support0.10.0 |
Legend
- Full support
- Full support