Peter Pan Peter Pan - 1 year ago 94
Javascript Question

Reversing a String with Recursion

I am getting into recursion and I wanted to do a simple thing as reversing a string. The function is working but I don't understand how and that makes me very frustrated.(the recursive part)

function reverseString(myString) {
if (myString == "") {
return "";
else {
return reverseString(myString.substr(1)) + myString.charAt(0);

Let's say I have a string "abcd". So the first loop would be:

"myString.substr(1)" makes from "abcd" -> "bcd" and then "charAt(0)" gets "b";

The result would be "bcd + b"? Or does "myString.charAt(0)" get executed when the recursion is finished?

I am completely lost ... how does the whole procedure look like?

Answer Source

No, all of the parameters that you are passing in to the recursive call are evaluated before the recursive call.

You are correct, myString.charAt(0) gets executed after your recursive call returns. This makes it more complex than so-called "tail recursion" or "head recursion" in which the recursive call is the last or first operation (respectively) in your recursive function. Writing a tail recursive or head recursive function can help certain compilers produce more efficient code and it also helps make your function more understandable, but it isn't "required".

Here's how it looks:

bcd + a
cd + ba
d + cba
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download