JavaScript Snippet

Reversing an Array (Iterative, Recursive, Copy)

Difficulty: Easy

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.

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

703 views

8

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.