What is Recursion?
Let’s get introduced to recursion.
We'll cover the following
What is Recursion?
Recursion is when a function calls itself again and again until it reaches a specified stopping condition. This is called a recursive function.
Recursion is the process of describing an action in terms of itself.
Why Recursion?
Recursive code is generally shorter and easier to write when compared to an iterative code. In general, the recursive code helps us avoid complex nested loops and is most useful for tasks that can be defined in terms of similar subtasks.
Format of a Recursive Function
Each recursive function consists of parts:
-
Base Case: The base case is where further calls to the same function stop, i.e, it does not make any subsequent recursive calls.
-
Recursive Case: The recursive case is where the function calls itself again and again until it reaches the base case.
The illustration below shows the flow diagram of a recursive function:
In a recursive program, the solution to the bigger problem is expressed in terms of the smaller problems, until the smallest problem reaches the base case.
Syntax of a Recursive Function
This is how a recursive function is typically implemented in JavaScript:
function RecursiveFunction() {
// Base Case
if (<baseCaseCondition>) {
return <some value>;
}
// Recursive Case
else {
return <recursive call and any other task>;
}
The base case leads to returning values directly, whereas in the recursive case, we call the respective function again.