Reverse a String: How this code work?

Tell us what’s happening:

Your code so far

function reverseString(str) {
   return (str === '') ? '' : reverseString(str.substr(1)) + str.charAt(0);


Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) coc_coc_browser/79.0.108 Chrome/73.0.3683.108 Safari/537.36.

Link to the challenge:

I have blurred out the solution, so any camper coming across this post would not just see the solution.

What part of the code do you not understand? Please be as specific as you can be.

i mean this part: return (str === ‘’) ? ‘’ : reverseString(str.substr(1)) + str.charAt(0);

i don’t understand when (str === ‘’)

That uses a ternary operator. You should review the following lessons:

Use the Conditional (Ternary) Operator

Use Multiple Conditional (Ternary) Operators

As far as the ( ) surrounding the str === '', that part is not necessary actually. It is just there to group the expression. You could remove the parentheses and the code would work the same. There are times when parentheses would be needed, but not in this case.


Hello @tuanldhe140929,

Per the challenge instructions, you will need to split the string into array, reverse the array, then join the array to complete this challenge. You don’t need a conditional statement to complete this challenge.

1 Like