What is reverse()?

reverse() reverses the order of an array's elements in place and returns that same array; use toReversed() (ES2023) when you need a reversed copy instead.

Mutation is the main gotcha

Because reverse changes the original, calling it on React state, props, a shared module-level array, or the result of a function you do not own causes subtle bugs. Typical example: reversing a list for display also flips the data used elsewhere.

Non-mutating options

  • arr.toReversed(): modern and explicit.
  • [...arr].reverse(): works everywhere.
  • arr.slice().reverse(): the older idiom.

Reversing strings

Strings have no reverse method. The common approach is [...str].reverse().join(""). Use spread rather than split(""), because spread splits by code points and keeps emoji and other astral characters intact. (For complex grapheme clusters such as flags or family emoji, use Intl.Segmenter.)

Iterating backwards without copying

If you only need to loop in reverse, a classic for (let i = arr.length - 1; i >= 0; i--) avoids creating a new array. findLast/findLastIndex search from the end directly.

Return value

reverse returns the same array reference (useful for chaining, dangerous if you assumed a copy).

Code example

js
1const steps = ["plan", "build", "test", "ship"];
2
3const reversedCopy = steps.toReversed();
4console.log(reversedCopy, steps); // ["ship", "test", "build", "plan"] ["plan", "build", "test", "ship"]
5
6const same = steps.reverse(); // mutates!
7console.log(same === steps, steps); // true ["ship", "test", "build", "plan"]
8
9// Reversing strings safely
10const reverseString = (s) => [...s].reverse().join("");
11console.log(reverseString("hello")); // olleh
12console.log("hi👋".split("").reverse().join("") === "👋ih"); // false - split breaks the emoji
13console.log(reverseString("hi👋")); // 👋ih
14
15// Grapheme-aware reverse for complex emoji
16const reverseGraphemes = (s) =>
17 [...new Intl.Segmenter("en", { granularity: "grapheme" }).segment(s)].map((x) => x.segment).reverse().join("");
18console.log(reverseGraphemes("a👨‍👩‍👧b")); // b👨‍👩‍👧a
19
20// Loop backwards without copying
21for (let i = reversedCopy.length - 1; i >= 0; i--) console.log(i, reversedCopy[i]);

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.

Open in study app