DEV Community

Magerman714
Magerman714

Posted on • Updated on

Recursion

How to Think About Recursion

Recursion is when a function calls itself in a return statement

This may be confusing at first - "won't this make an infinite loop?" you might ask. The key in recursive functions is that every time they call themselves, they change their parameters slightly so that an included if statement can check for an end state and properly stop the function from continuing

for example:

function recur(count){
if(count === 0){
return;
}
console.log(count);
return recur(count - 1);
}

The above function would print the numbers from count down to 1 to the console; note that it would not print "0" because when count eventually becomes 0, the if statement will simply return. If we wanted to print 0 as well, we'd need another console.log within the return statement.

Another looping mechanism for your repertoire

The best way I have found to think of recursion is that it's simply another way to do loops. It has all the pieces of, say, a for loop, just in a different order. For instance, if we wanted to print the above function using a for loop it would look like this:

function forLoop(count){
for(let i = count; i > 0; i--){
console.log(i);
}
}

Let's break this down:

the first part of the for loop, "let i = count", sets up how many iterations we will go through based what argument is passed to the function. No "i" variable is needed in the recursive function, but the argument passed to "count" still serves the same purpose.

The second part of the for loop, "i < 0", indicates the stop statement for the loop; the loop will continue iterating so long as i is greater than 0. The same functionality is served by the if statement at the top of the recursive function; once count = 0, the loop is ended by a return statement.

The third part of the for loop, "i--", is what changes the variable that is tested for in order to stop the function once it has gone through all the iterations we want it to, and to prevent it from becoming an infinite loop. The same purpose is covered by the return statement at the end of the recursive function: "return recur(count - 1);".

So if we think about this, if count = 5, then the first time we go through the recursive function it will console.log count (5), then it will return itself with count - 1 as the argument, so it will essentially return "recur(4)". It will do this until the if statement's condition is met (i.e. it runs "recur(0)"), at which point it will hit the return statement and stop iterating.

In summary, a recursive function has all of the pieces of a for loop, just in different locations.

I hope this helps your understanding of recursion!

Top comments (0)