What is Recursion in JavaScript?
Recursion is a problem-solving technique in programming. In this article, you will learn how to use recursion in JavaScript.
What Is Recursion?
An object is recursive if it contains an identical copy of itself.
Recursion occurs when the outcome of a process depends on a previous version of itself.
What is a Recursive Function?
A recursive function is one that calls itself somewhere within its function body. A basic example is shown below.
function recursiveFunction() {
// some code here...
recursiveFunction()
}
In this example, recusriveFunction
will keep calling itself until the desired outcome is achieved.
So how do you tell the function when to stop calling itself? You do so by including a base condition.
The Three Parts of a Recursive Function
Every recursive function you write must include these three elements:
The function definition
The base condition
The recursive call
If any of these elements is missing, your recursive function won’t work as you expect. Let’s take a look at each element.
How to define a recursive function
You define a recursive function in JavaScript just like any other JavaScript function.
function recursiveFunction() {
// some code here...
}
The only difference is that you’ll need to include a base condition and recursive call within the function.
What is a base condition?
A base condition let’s the recursive function know when to stop calling itself.
The recursion ends once the base condition is met.
function recursiveFunction() {
if(base condition) {
// stops recursion if condition is met
}
// else continue recursion
recursiveFunction();
}
Why do you need a base condition?
You need a base condition to let the recursive function know when to stop running.
function doSomething(action) {
console.log(`I am ${action}.`)
doSomething(action)
}
doSomething("running")
Without a base condition, you will encounter infinite recursion.
This will cause your function to exceed the maximum call stack, like in this example:
Maximum call stack exceeded when there's no base condition
The Call Stack keeps track of what functions are currently running and the functions that are within them.
The call stack has a limit. And since a recursive function without a base condition will run infinitely, it exceeds the call stack's limit.
The base condition provides a way to break out when the function gets the desired output.
Example of a recursive function
Let's see a simple example of a recursive function.
function doSomething(depth) {
if(depth === 0) { // base condition
console.log("I AM DONE!")
return
}
console.log("I'm doing something.")
doSomething(depth - 1) // recursive call
}
doSomething(3)
Here is the result when you pass the number 3
to the doSomething
function.
The base condition for the doSomething
function is depth === 0
. Each time the function is called, it first checks if the base condition is met.
If yes, it prints I AM DONE!.
If not, it continues with the rest of the code in the function. In this case, it will print I'm doing something, and then call doSomething
again.
The recursive call
The recursive call is where the function calls itself again. In the doSomething
function, the recursive call is the line below.
doSomething(depth-1)
Note what happens when the function calls itself. A new parameter depth - 1
is passed on each new recursive call. This parameter differs from that of the previous call.
The function will keep calling itself until the newest parameter satisfies the base condition.
Recursion vs Loops
Recursion and loops work in similar ways. Every recursive function you write has an equivalent solution with a loop.
For example, you can create a function to find the factorial of a given number using both recursion and loops.
How to find the factorial with a loop:
function findFactorial(n) {
// Initialize result to 1
let factorial = 1;
// Loop from 2 to n and multiply
for (let i = 2; i <= n; i++) {
factorial *= i;
}
return factorial;
}
// Example usage:
console.log(findFactorial(5)); // Output: 120
To find the factorial using a loop:
Initialize a variable
factorial
with a value of1
.Initiate the loop from number
2
. The loop will continue running untiln
For each iteration, you multiply the current value of
factorial
byi
. And you increase the value ofi
by 1 untili
is greater thann
.
Finally, you return the value of the factorial when the loop finishes running.
How to find the factorial with recursion:
You can create the same solution with a recursive function.
function findFactorial(n) {
if (n === 0) return 1
let factorial = n * findFactorial(n - 1)
return factorial;
}
findFactorial(5) // 120
First, you need a base condition
n === 0
.You also need the recursive call
findFactorial(n - 1)
to ensure the number keeps reducing at each call by passing a new parameter ofdepth - 1
.You then multiply the result with the previous number
n * findFactorial(n - 1)
until the base condition is met.
So which is better – recursion or loops?
There's no right or wrong answer. It's up to you to decide.
Depending on the problem you're solving, you may choose one over the other.
Sometimes, like in the factorial example, recursion leads to shorter and more readable code. However, recursive functions are not always intuitive.
For simple iterations, loops are often more straightforward and easier for others to understand.
Conclusion
In this article, you've learned what recursion is and how to create recursive functions in JavaScript.
Reading and writing recursive functions might be confusing at first. But remember, what makes recursive functions different from regular functions are the base condition and the recursive call.
Thanks for reading. And happy coding!
Subscribe to my newsletter
Read articles from Chidi Okeke directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by