The challenge
Write reverse(text) that returns the text backwards.
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.
It prints
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
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.