What is a Recursive Function?

Jeff Cuartas
3 min readJul 12, 2021

In order to have a full understanding of how algorithms and data structures in JavaScript work, it is important to be familiar with the concept of recursion.

Recursions refers to the process of a function calling itself. In JavaScript, we can think of writing functions two ways: an iterative way or a a recursive way.

If you’ve complete any easy LeetCode challenges, then chances are you have already written iterative functions. For example, a simple loop that iterates through an array.

You may be wondering why if we already have one way of writing functions in an iterative way, then why do we need to write functions recursively?

The first reason is that recursive functions exist everywhere and are used a lot so it’s critical for us to understand recursive functions so that we can also understand the code of others. Some examples of where you will encounter recursive functions are in DOM traversal algorithms, complex data structures, and code that uses JSON.parse/JSON.stringify.

The second and perhaps more useful reason is that writing recursive functions is sometimes an easier and cleaner alternative to iteration.

Writing a Recursive Function

One of the most common recursive functions you may encounter is function that takes the factorial of a number. This type of function is also a great way to begin to understand how recursion works.

The factorial of a number is the product of all positive integers of a number down to 1. For example, the factorial of 4 (usually written as 4!) is 4 x 3 x 2 x 1 = 24.

In the function above, we are finding the factorial of a given number through a recursive manner. As you may notice our function calls itself within the function.

There are two important elements that make up a basic recursive function an end point (also known as a base case) which tells our function when to stop and a different input that tells our function to look at an increasingly smaller subset of data.

In factorialRec, the base case is reached when our function that is called recursively is equal to one. And write below the base case, is the input that changes— each time factorialRec is called our original input is decreased by one.

Therefore, our call stack (function that is invoked) has a smaller input each time and once the input reaches 1 the function will return 1 as well as all the return values of the functions in the call stack.

Conclusion

Although we could have written our factorial function in an iterative way, as you can see through this example, writing recursive functions can sometimes be a more straightforward way of writing logical code that is clean to read and economical.

--

--