transformation
Array.prototype.reverse
Reverses the order of elements in place and returns the same (mutated) array. Reach for it when you truly want to reverse the source; otherwise use toReversed().
arr.reverse() Parameters
| Parameter | Purpose |
|---|---|
| return value | The same array reference, now reversed |
| mutation | Modifies the original array in place (use toReversed for a copy) |
Examples
const a = [1, 2, 3]; a.reverse(); console.log(a); Logs: [3, 2, 1] — original is mutated
console.log(['a','b','c'].reverse()); Logs: ['c', 'b', 'a']
const a = [1,2,3]; const b = a.toReversed(); console.log(a, b); Logs: [1, 2, 3] [3, 2, 1] — toReversed is the ES2023 non-mutating version
const a = [1, 2, 3]; const b = a.reverse(); console.log(a === b); Logs: true — reverse returns the same array reference
Gotcha
MUTATES the source. If you also stored the pre-reverse array in a variable, it is now reversed too. Use `toReversed()` (ES2023) for a copy.
Related methods
Array.prototype.sort
Sorts the array in place and returns the same array; without a compareFn elements are coerced to strings and sorted lexicographically. Reach for it when you need ordered data — but always pass a compareFn for numbers.
Array.prototype.slice
Returns a shallow copy of a portion of the array from start (inclusive) to end (exclusive) without modifying the source. Reach for it to extract a range or to clone an array (`arr.slice()`).
Array.prototype.at
Returns the element at the given integer index, supporting negative values that count from the end (ES2022). Reach for it as the clean replacement for `arr[arr.length - 1]`.
Array.prototype.flat
Returns a new array with all sub-array elements concatenated up to the specified depth (ES2019). Reach for it to unnest arrays of arrays without a manual reduce.
Array.prototype.flatMap
Maps each element with a callback, then flattens the result by one level (ES2019). Reach for it when a mapper naturally returns arrays and you want a single flat list back.