What is Recursion?

What is Recursion?

Recursion occurs when a function calls itself repeatedly until it reaches a specified stopping condition. Such a function is called a recursive function.

Recursion is the process of describing an action in terms of itself.

Why use Recursion?

Press + to interact
Benefits of recursion
Benefits of 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

A recursive function consists of two main parts:

  • Base Case: The base case is where all further calls to the same function stop, meaning that it does not make any subsequent recursive calls.

  • Recursive Case: The recursive case is where the function calls itself repeatedly until it reaches the base case.

The illustration below displays the flow diagram of a recursive function:

Press + to interact
Workflow of a recursive function
Workflow 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 <someValue>;
}
// Recursive Case
else {
return <someOperationsAndRecursiveCall>;
}
}

The base case leads to returning values directly, whereas in the recursive case, we call the respective function again.