Code Snippets
/

Reversing an Array (Iterative, Recursive, Copy)

Reversing an Array (Iterative, Recursive, Copy)

Reversing an array is a one-liner if you do not mind mutating the input, and a slightly different one-liner if you do. This snippet covers the built-in `reverse()` mutating call alongside the immutable `toReversed()` and spread alternatives, the two-pointer in-place swap that interviewers ask about, and a recursive form for the recursion lesson. Production code should pick one of the first-accordion forms; the others are for understanding.

JavaScript
Easy
3 snippets
arrays
recursion
array-manipulation-patterns

705 views

8

// Mutating: Array.prototype.reverse() flips in place and returns the same array.
const nums = [1, 2, 3, 4, 5];
nums.reverse();
console.log(nums); // [5, 4, 3, 2, 1]  (original mutated)

// Immutable via spread: copy first, then reverse the copy.
const original = ['a', 'b', 'c', 'd'];
const reversed = [...original].reverse();
console.log(original); // ['a', 'b', 'c', 'd']  (untouched)
console.log(reversed); // ['d', 'c', 'b', 'a']

// Immutable via Array.prototype.toReversed() (Node 20+, ES2023).
const src = [10, 20, 30];
console.log(src.toReversed()); // [30, 20, 10]
console.log(src);              // [10, 20, 30]

Array.prototype.reverse() reverses in place and returns the same array, so nums.reverse() and [...nums].reverse() look almost identical but have very different semantics: the first form mutates the original and the second leaves it untouched. The newer toReversed() (ES2023, Node 20+) returns a reversed copy in one call, which is more declarative. Default to toReversed() if your runtime supports it; otherwise [...arr].reverse() is the immutable fallback. Reach for the bare reverse() only when you specifically want the mutation.