Reverse a string

“Backwards”, a White belt challenge from the CurlyScript Dojo. It uses what Grade 5: Loops: Doing Things Over and Over teaches, and 3 tests check your answer.

The challenge

Write reverse(text) that returns the text backwards.

Example
reverse("hello")  // "olleh"

Try it

Write your answer below, then press Check my answer. Your code runs right here in your browser, and the tests tell you what works.

What the tests check

  • reverse("hello") gives "olleh"
  • reverse("Paris") gives "siraP"
  • reverse("") gives ""

Hints

Stuck? Open one hint at a time. Try again after each one.

Hint 1

Start with an empty string and loop from the last index down to 0.

Hint 2

Or loop forwards and put each character in front: result = char + result.

A solution

There’s always more than one right way. Read it, make sure you understand it, then try writing it yourself without looking.

Show one possible solution
Solution
function reverse(text) {
  let result = "";
  for (const char of text) {
    result = char + result;
  }
  return result;
}

Learn what you need

This exercise uses what Grade 5: Loops: Doing Things Over and Over teaches. Read those notes first if any of it is new.

Practice makes it stick

CurlyScript is a free game that teaches JavaScript from zero: short lessons, an explanation after every answer, and Dojo challenges like this one.

Start learning