JavaScript Recursion

Sanjana Human In Tech
2 min readDec 12, 2023

--

Javascript Rescursion

Recursion is a programming concept where a function calls itself to resolve the problem.

This is a simple term.

The syntax for the recursive function is:

function recursion() {
recursion();
}
recursion();

To must remember; recursive function to be called with base condition otherwise it will go to infinite loop and you will not be able to see the result.

It behaves anonymously.

That means A recursive function must have the condition to meet the result.

we can use if..else statement where once branch called similar function and other don’t to prevent the recursion.

so, generally it looks like

function(recursion) { 
if(condition) {
recursion();
} else {
//stop calling recursion
};
}
recursion();

Another example of Recursion is to find the factorial.

Remember, in maths we studied what is factorial ?

example : 5!=5×4×3×2×1=120.
In general, for a non-negative integer n, the factorial n! is the product of all positive integers less than or equal to n:

n!=n×(n−1)×(n−2)×…×2×1.

It’s important to note that by convention, the factorial of 0 is defined to be 1 (0!=10!=1).

// Example: Calculating the factorial of a number using recursion

function factorial(n) {
// Base case: factorial of 0 or 1 is 1
if (n === 0 || n === 1) {
return 1;
} else {
// Recursive case: n! = n * (n-1)!
return n * factorial(n - 1);
}
}

// Testing the factorial function
console.log(factorial(5)); // Output: 120

In this example, the factorial function calculates the factorial of a number using recursion.

The base case checks if the input n is 0 or 1, in which case the function returns 1.
Otherwise, it recursively calls itself with the argument (n - 1) until the base case is reached.

Here’s a step-by-step breakdown of how factorial(5) is calculated:

  1. factorial(5) calls factorial(4)
  2. factorial(4) calls factorial(3)
  3. factorial(3) calls factorial(2)
  4. factorial(2) calls factorial(1)
  5. factorial(1) returns 1 (base case)
  6. factorial(2) returns 2 * 1 (result of 2 * factorial(1))
  7. factorial(3) returns 3 * 2 (result of 3 * factorial(2))
  8. factorial(4) returns 4 * 6 (result of 4 * factorial(3))
  9. factorial(5) returns 5 * 24 (result of 5 * factorial(4)), which is 120.

This is a simple example, but it illustrates the basic idea of recursion. When using recursion, it’s crucial to have a base case to prevent infinite recursion and ensure that the function eventually terminates.

Thank you for reading this article! Don’t forget to clap o

If you have any queries related to ReactNative, I’m always happy to help you. You can reach me on LinkedIn and Gmail.

--

--

Sanjana Human In Tech
Sanjana Human In Tech

Written by Sanjana Human In Tech

A React Native front-end enthusiast and dedicated development engineer, eager to expand knowledge on development techniques and collaborate with others.

No responses yet