Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

cannot understand logic of recursion

This function has to return reversed string. For example, “dog” -> “god”.
It works correctly but I don’t understand the logic and I need explanation

function reverse (str) {
   if (str.length <= 1) return str;
   return reverse(str.slice(1)) + str[0]
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Explaination

Firstly, you call reverse(“dog”) and it return reverse(“og”)+”d”
Then the reverse(“og”) continue to run again. It returns reverse(“g”)+”o”
The last one, reverse(“g”) only returns “g” since the if statement is true

Then you plug the reverse(“g”) to the reverse(“g”)+”o”, as a result “go” is returned
Finally, plug reverse(“og”) to reverse(“og”)+”d”, which is “go”+”d”, as a result “god” is the output

The flow

  • (1) reverse("dog") called -> return reverse("og")+"d"
  • (2) reverse("og") called -> return reverse("g")+"o"
  • (3) reverse("g") called -> return "g" (if statement)
  • (4) plug (3) to (2) -> return "g" + "o" -> "go"
  • (5) plug (4) to (1) -> return "go" + "d" -> "god"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading