If you are learning JavaScript, you must have come across the term “recursion in JavaScript”. Recursion is a powerful JavaScript technique through which a function can call itself to solve the smaller divisions of a huge problem. At first, you may find it confusing, but as you understand the basic idea, it becomes a very useful tool.
In this blog, we will talk about recursion in JavaScript in a step-by-step process, along with practical examples. So let’s get started!
Table of Contents:
What is Recursion in JavaScript?
Recursion in JavaScript refers to the technique where a function calls itself to solve a smaller part of the problem until it gets a solution. In simple terms, it is like breaking a big task into smaller tasks of the same kind and solving each task one at a time.
Boost Your Resume With Real Skills
Join Our Web Dev Course
Syntax for Recursion in JavaScript
Given below is the syntax for Recursion in JavaScript:
function recursiveFunction(parameters) {
// It is the base case (stopping condition)
if (baseCase) {
return baseCaseValue;
}
// It is the recursive case (Function calls itself)
return recursiveFunction(modifiedParameters);
}
Key Components:
- Base Case: The base case is the state that prevents the recursive definition function from calling itself. This is necessary because the function will never stop running and lead to a stack overflow. For example, while factorial calculation, the base case is when the number is 0 or 1.
- Recursive Case: The recursive case is basically that part of the function where it calls itself using a changed or smaller input. This change is important because it helps to move the function closer to the base case, which is the condition that is used to stop the recursion. Without moving towards the base case, the recursion would occur endlessly. For example, while calculating a factorial, the recursive case is written as n * factorial(n – 1). Here, each call is used to reduce the value of n by 1. This process eventually reaches the base case when n becomes 0 or 1.
Example: Factorial of a Number
Given below is an example of recursion in JavaScript.
Code:
Output:
Explanation:
The above JavaScript code is used to define a recursive function. It is used to calculate the factorial of a number. At first, it checks the base case; if you set the input n as 0 or 1, it will return 1 as the factorial of 0 and 1 is 1. If it does not return 1, it uses the recursive case by calling itself with n – 1, and then multiplying the result by n. This keeps on continuing until the base case is reached. For example, factorial(5) (when called) returns 5 * 4 * 3 * 2 * 1 or 120.
Infinite Recursion in JavaScript Prevention with the Use of if…else Statement
While writing a recursive function JavaScript example, one of the most important things you need to handle is infinite recursion. Without a stopping condition, the function will go on to call itself endlessly, which leads to a stack overflow error. To avoid this issue, you can use the if…else statement to define a base case, which works as the exit point of the recursion.
Now, let us look at an example for your better understanding.
Code:
Output:
Explanation:
In the above function countdown(n), the if…else statement is used to check if the input number n is less than or equal to 0. This is called the base case. If it is true, the function prints “Done!” and stops calling itself. If it does not, then it prints the current number and calls itself with n – 1. In this way, each call gets closer to the base case, which prevents infinite recursion.
Get 100% Hike!
Master Most in Demand Skills Now!
Recursion vs Loop in JavaScript
The difference between Recursion and loops in JavaScript is given below in tabular format:
Feature |
Recursion |
Loop |
Definition |
It is a type of function that calls itself |
It is a block of code that runs repeatedly |
Structure |
It uses function calls. |
It uses keywords like for, while, or do-while. |
Base Case/Condition |
It requires a base case in order to stop recursion |
It requires a condition to stop the loop. |
Memory Usage |
It uses more memory (stack per call). |
It uses less memory. |
Performance |
It works slowly due to function call overhead. |
It is usually faster and more efficient. |
Best Use |
It is suitable for tree/recursive problems. |
It is appropriate to use in repetitive tasks and basic iterations. |
Risk |
It may cause a stack overflow if not written well. |
It is safer in terms of memory usage. |
Implementation of Recursion in JavaScript
Given below are the important recursive function JavaScript examples which is important for you to understand.
1. Factorial of a Number
It is used to calculate the factorial of a number using recursion.
Code:
Output:
Explanation:
The above JavaScript function is used to calculate the factorial of a number using recursion. It takes a number n as input. The base case is checked with the help of the if condition; in case n=0 or n=1, the function returns 1. This is because the factorial of 0 and 1 is 1. If the condition is not met, the else block runs, where the function calls itself with n-1, and then the result is multiplied by n. This is done until the base case is reached. For example, factorial(7) (when called) returns 7 * 6 * 5 * 4 * 3 * 2 * 1, which is 5040.
2. Countdown
It is used to print a countdown from a given number to 1.
Code:
Output:
Explanation:
The above code is used to define a recursive function, countdown, that prints numbers from n to 1. If n is less than or equal to 0, it prints “Done!” and the function stops. Otherwise, the function prints the current number and then calls itself with n – 1. If you call countdown(10), it prints the numbers from 10 to 1, followed by “Done!”.
3. Sum of an Array
It is used to add all elements in an array using recursion.
Code:
Output:
Explanation:
The above code is used to define a recursive function, sumArray, which adds all the elements in an array. When the array is empty, it returns 0. Otherwise, it adds the first element to the sum of the remaining elements in the array by calling itself with the rest of the array. For example, the sum of the array [1, 2, 3, 4] gives 10 as the output.
4. Fibonacci Sequence
It is used to return the nth Fibonacci number using recursion.
Code:
Output:
Explanation:
The above code is used to define a recursive function, fibonacci, that is used to find the nth Fibonacci number. It will give back n in the case of n being 0 or 1 (base case). Otherwise, it adds fibonacci(n-1) and fibonacci(n-2) in order to get the result. This code prints the first 6 Fibonacci numbers from 0 to 5.
5. Reverse a String
It is used to reverse a string using recursion.
Code:
Output:
Explanation:
The above code uses recursion to reverse a string. If the string is empty, it then returns an empty string (base case). Otherwise, it reverses the rest of the string and adds the first character at the end. In the above example, “Hello Intellipaat” is returned as “taapilletnI olleH”.
6. Find Maximum in an Array
It is used to find the largest number in an array.
Code:
Output:
Explanation:
The above code is used to find the maximum number in an array using recursion. When a single element is left, it returns the single element (base case). Otherwise, it compares the last element with the largest number of the remaining elements. In the case of array [3, 8, 12, 5, 1], it gives 12.
7. Calculate Power (Exponentiation)
It is used to calculate the base^exponent with the help of recursion.
Code:
Output:
Explanation:
The above code is used to define a recursive function, power, which calculates the result of raising a base to a given exponent. In case it has 0 as an exponent, it will give 1 (base case). This is because any number raised to the power of 0 is 1. Otherwise, it multiplies the base by the result of calling the function with the exponent reduced by 1. For example, power(2, 4) is calculated as 2*2*2*2, which gives 16 as output.
Best Practices
Some of the best practices for recursion in JavaScript are mentioned below:
1. In order to prevent infinite recursion, you are supposed to have a base case at all times. Without the base case, the function will run endlessly and cause a stack overflow.
2. Each recursive call is supposed to bring the input closer to the base case. If it doesn’t, the function will never stop running.
3. Recursive calls may cause a memory problem, especially when there are too many recursive calls. For large inputs, you can use loops instead of recursion.
4. If your recursion needs to carry extra values, you should use a separate helper function that helps to keep the main function clean.
5. Do not make your reasoning too complicated. It is easier to understand and debug a good and simple recursive structure.
6. It is more memory-efficient to write some functions in a tail-recursive manner, although that is not always done by JavaScript engines.
7. You need to use recursion only when the problem is naturally recursive. For simple repetition tasks, you can use loops.
Conclusion
In JavaScript, recursion is a helpful method in which a function calls itself to address minor aspects of a problem. It is important for you to understand how to write a base case and a recursive case, because it will help you to solve many problems like factorials, Fibonacci series, or working with arrays and strings. Although learning recursion can be confusing at first, with regular practice, it becomes easy to use. Always remember to follow the best practices to avoid common mistakes like infinite recursion. Once you understand how recursion works, it becomes an important tool in your JavaScript journey.
If you want to learn more about JavaScript, go through our JavaScript Interview Questions, and do not forget to subscribe to our Web Development course.
Recursion in JavaScript – FAQs
Q1. Can I use recursion to traverse the DOM in JavaScript?
Sure, the structure of nested DOM elements is often navigated and processed with the help of recursion.
Q2. Is recursion supported in all JavaScript environments, including browsers?
Recursion is supported everywhere in JavaScript, such as in browsers and in Node.js.
Q3. How can you debug a recursive function in JavaScript?
Recursive functions can be debugged step by step through console.log() or by the browser developer tools.
Q4. Is tail recursion optimized in JavaScript automatically?
Most JavaScript engines do not currently support tail call optimization.
Q5. Can recursion replace loops in all cases?
In technical terms, yes, but loops are faster and recommended when doing simple iterations.