One of the most important concepts in computer science for new students/developers to learn is recursion. This is at the heart of a lot of practical and useful algorithms that can help us solve problems clearly and concisely. When learning how to program, students start with iteration or loops to get the answer. Nevertheless, recursion might solve the problem in a more elegant way with less code and easier to understand.
In this article, we are going to cover recursion using JavaScript in the examples. However, the concept itself applies to all modern programming languages.
First, it is necessary to define recursion to have an idea of what it is. Recursion is when a function calls itself by solving parts of a larger problem until solving the larger problem and its totality. Or the recursion definition provided by Malik (2013) as “the process of solving a problem by reducing it to smaller versions of itself”.
Another way to see a recursion is like a loop of a function calling itself from inside the function body until it reaches a point of returning the value. As the simplest version for the sake of explanation, a recursive function would be like the following:
The factorial is the product of all the positive integers that are less or equal to n. To illustrate, 4! = 4 * 3 * 2 * 1 = 24. But, the factorial of zero is one 0! = 1. Thus, if you are trying to find the factorial of zero, the value will be one and not zero. This is a good example because it is simple enough to grasp what could be solved with a recursive function.
The first step is to get the base case which is the value that will be returned directly from the function. For our factorial function, the base case is when n is one or zero, it will return 1. Thus, if we use factorial(1) or factorial(0), one will be returned by the function.
Then, the general case is the one that must be solved recursively. The general case for the factorial function is multiplying the current number with the number returned by the factorial function.
function factorial(n) {
if(n <= 1) return 1;
return n * factorial(n - 1);
}
The following is an illustration of what is happening when calling factorial(4).