Question about Recursion

I see this function all the time when talking about recursively reversing a string:

 function reverseStr(str) {
    if (str.length <= 1) {
        return str;
    } else
        return reverseStr(str.substr(1)) + str.charAt(0);

Now im sure im not asking the ‘right’ question but i still cant understand this. My questions are:

  1. Why does the str.length method work here? I know that recursion is explained as a form of iteration , but in a for loop you have the increment/decrement expression (i++/i–). I don’t see that here. Is it implicit in a function somehow? What Im basically asking is, how the string in question is ‘getting smaller’ on each recursive call so that str.substr(1) call works, and the eventual ‘base case’ is satisfied. How is str.length <=1 when if you use the substr method on a string in the console, the length isn’t changed of course.
1 Like

.substr() doesn’t change original string, just returns what is asked for i.e. made a copy of it. Try console logging it.
console.log(str.substr(1)+" "+str);
As you can see its logging chunk of string and string itself. Try it, see it what happens. Same is with charAt().

The for loop is composed of 3 parts:

1- State declaration (i = 0 usually, you can even declare more)
2- End condition (usually < .length or <= end number)
3- After-block execution expression that gets evaluated after every iteration, usually increments a counter “i” (or decrements in reverse)

With recursion as a loop, you:

1- There is no state (unless explicitly required), but rather you keep track of the elements inside the parameter/argument interaction
2- The end condition is usually within the first if statement in the function (like .length > 0 etc), or in some functional languages, guards and pattern matching (like haskell, ML and elixir).
3- This step is done by calling the function again but with different arguments, usually subtracting/adding a number to a parameter (or counter) or making an array smaller by passing a subset of it (which is what .substring(1) does: pass the “tail” of the string, the rest of the characters).