JavaScriptArrays
Array. prototype. reverse()
Reverses the order of the array’s elements in place.
- Returns
- The same, reversed array.
- Changes the original
- Yes
Example
#JavaScript
const levels = [1, 2, 3, 4]
levels.reverse()
console.log(levels)
console.log('kayak'.split('').reverse().join(''))Console
[4, 3, 2, 1]
kayak
Definition and usage
#The reverse() method flips the order of the elements: the first becomes the last, and the last becomes the first. It changes the original array and returns a reference to it.
It’s handy, for example, for showing the newest entries at the top when the data arrives in chronological order.
The non-mutating version is toReversed(). In older code you’ll also see [...array].reverse().
Syntax
#Syntax
array.reverse()Browser support
#Widely available
Works in all modern browsers, phones included. You can use it without worry.
- Chrome
- Edge
- Firefox
- Safari
Good practices
#- Watch out:
const reversed = items.reverse()also reversesitems, because it’s the same array. - To reverse a string, chain
split(""),reverse(), andjoin("").
Related entries
#- Array.prototype.toSorted()Returns a sorted copy of the array, leaving the original unchanged.
- Array.prototype.sort()Sorts the array’s elements in place and returns the same array.
- Array.prototype.join()Joins the array’s elements into a single string with a chosen separator.
- String.prototype.split()Splits a string into an array of pieces based on a separator: a character, a string, or a regular expression.
- Array.prototype.toReversed()Returns a new array with the elements in reverse order, without changing the original.
Spotted a mistake or missing an example? Write to us.