Skip to main content
πŸ” Recursion

Reverse a String

Strings can be sliced just like arrays, so the same "first / rest" idea works β€” but for a reverse, the order flips. Take the first character and stick it on the end of the reversed rest. An empty string reverses to itself.

function reverse(str) {
  if (str === "") return "";              // base case
  return reverse(str.slice(1)) + str[0];  // reverse the rest, THEN add first
}
reverse("abc"); // "cba"

The key is putting str[0] after the recursive call. That's what pushes the first character to the back: reverse("bc") + "a" β†’ "cb" + "a" β†’ "cba".

Your task

Write reverse(str) that returns str reversed, using recursion (no .reverse() and no loops).

⚑ 40 XP

🧱 Code blocks

Drag a block into the editor, or tap it to drop it in where your cursor is. Add them in order to build your answer.

solution.jsRuns in your browser
Loading editor…
Tests4 to pass
"hello" β†’ "olleh"
empty string
"a" β†’ "a"
"Boots" β†’ "stooB"

Run your code to check these.