JavaScript Reference ยท Array
Array.prototype.reverse()
Reference for JavaScript Array.prototype.reverse(): reverse the order of elements in place, what it returns, copying first, and the toReversed() alternative.
The reverse() method reverses the order of an array's elements, so the first becomes the last and the last becomes the first. It changes the array itself and also returns a reference to that same array.
Because it mutates, call it on a copy when you need to keep the original order. Modern JavaScript offers toReversed() for exactly that.
const list = [1, 2, 3]; list.reverse(); // list is now [3, 2, 1]
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
array.reverse()
Parameters: none.
Return value: the same array, now reversed (not a copy).
Exceptions: a TypeError if the array is frozen.
Usage notes
- It mutates and returns the same array.
const b = a.reverse()leavesaandbpointing to one reversed array. - Copy first with
[...a].reverse()ora.slice().reverse(), or usea.toReversed(), which returns a new array and leaves the original alone. - Shallow only. Only the order of the top-level elements changes. Nested arrays and objects are not reversed inside.
- Reversing a string needs
split(""),reverse()andjoin(""). This splits by UTF-16 code units, so emoji and combined characters can break; use[...text]for code points, though even that can split grapheme clusters. - Sparse arrays: holes are kept and move to their mirrored positions.
- Reverse sorting: to sort in descending order, pass a comparator to
sort()instead of sorting and reversing. - Iterating backward without changing anything is often simpler with a
forloop that counts down, orfindLast()when you are searching. - Generic. It works on array-likes through
Array.prototype.reverse.call(obj).
Browser support
Array.prototype.reverse() is part of ES3 and works everywhere. The copying alternative toReversed() is newer, so check a compatibility table before relying on it for older browsers.