How to write a recursive function
Daniel Zaltsman
Posted on February 2, 2020
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.
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.
This function will only run once, but we need it to continue calling itself until an execution of the function reaches the base case.
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:
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.
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...
Posted on February 2, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.