What is Recursion?
Let’s get introduced to recursion.
We'll cover the following
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?
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:
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 Caseif (<baseCaseCondition>) {return <someValue>;}// Recursive Caseelse {return <someOperationsAndRecursiveCall>;}}
The base case leads to returning values directly, whereas in the recursive case, we call the respective function again.