notforever notforever - 1 year ago 70
Javascript Question

Please explain this recursive javascript function

I was in codewars this morning and there is this Kata asking for a function to reverse a string passed as parameter through recursion method.

The best solution listed for this problem was this.

function reverse(str) {
return str.length > 1 ? reverse(str.slice(1)) + str[0] : str;

I researched for this all this morning and I still don't know what is happening here:

+ str[0]

Can somebody please clarify this for me?

Answer Source

The essence of the function is the following:

  1. Take the substring from the second character to the last
  2. Apply the reverse function recursively
  3. Take the first character and append it to the end of the result of the recursive call
  4. Return the result

This results in the following logic, the (recursive) function calls indicated by brackets:

(A B C D E)
((B C D E) A)
(((C D E) B) A)
((((D E) C) B) A)
(((((E) D) C) B) A)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download