DEV Community

Daniel Zaltsman
Daniel Zaltsman

Posted on • Edited on

How to write a recursive function

What is recursion/recursive function?

Simply put, a recursive function is a function that calls itself during execution.

When and why will you need this?

There are problems in programming that may be easier solved through recursion rather than iteration, so you may end up using it as a solution. There's a greater space requirement for recursion, but it is simpler to write and easier to read. Some problems are also inherently recursive and it is preferred to use a recursive solution.

The code

Recursion helps to solve smaller instances of a problem. In this problem, we are asked to push a number n times into an array and return it.

The first thing we need to figure out is the base case/base condition, which is the condition that stops the function from calling itself otherwise the function will loop infinitely and cause a stack overflow.

Image from Gyazo

In the first call, result is set to an empty array by default. It will check the if statement to see if the result length is the same as the times argument.

Now we have to add the block that will put us closer to our base case.

Image from Gyazo

This function will only run once, but we need it to continue calling itself until an execution of the function reaches the base case.

Image from Gyazo

Now the function will call itself until the base case is called. But we are missing one thing here. As it stands, the last call will return the value to the second-to-last call due to the else block. But, the else block does not return the value of that call. The last call will break the loop and return it to the previous call stack, but will not return anything. Here's the fix:

Image from Gyazo

This will allow the return value of the last stack to be passed up to the second-to-last, and so on, until it reaches the first stack, which is then returned to the console.

Image from Gyazo

So there you have it! Give it some practice, play around with it, and the mystery of recursion will unfold itself to you, over and over and over...

Top comments (0)