Open In App

How to Understand Recursion in JavaScript ?

Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will understand the basic details which are associated with the understanding part as well as the implementation part of Recursion in JavaScript.

Let us first understand what exactly is Recursion.

Recursion:

  • We could define recursion formally in simple words, that is, function calling itself again and again until it doesn’t have left with it anymore.
  • We may think of recursion (informally) as like running on a racing track again and again but each time the laps getting smaller and smaller.
  • As we have seen that recursion is function keep calling itself again and again and eventually gets stopped at its own, but we may also realize a fact that a function doesn’t stop itself.
  • Therefore to make function stop at some time, we provide something calling Base Case, which lets any function realize that “Yes, its time to get terminated!”.
  • After giving the base case condition, we implement the recursion part in which we call function again as per the required result.
  • Some common examples of recursion includes “Fibonacci Series”, “Longest Common Subsequence”, “Palindrome Check” and so on.
  • We may also think recursion in the form of loop in which for every user passed parameter function gets called again and again and hence produces its output as per the need,

Now that we have understood all the basic things which are associated with the recursion and its implementation, let us see how we could implement it by visualizing the same through the following examples-

Example 1: In this example we will be implementing a number decrement counter which decrements the value by one and prints all the numbers in a decreasing order one after another.

Javascript




<script>
    let decrementCounter = (number) => {
 
        // Base case condition....
        if(number === 0) return ;
        console.log(number);
        decrementCounter(number - 1);
    }
    decrementCounter(5);
</script>


Output:

5
4
3
2
1

Example 2: In this example, we will be developing a code that will help us to check whether the integer we have passed is Even or Odd. By continuously subtracting 2 from a number, the result would be either 0 or 1. So if it is 0 then our number is Even otherwise it is Odd.

Javascript




<script>
    let checkNumber = (number) => {
 
        // Two base case conditions.....
        if(number === 0) return (number + " is even");
        if(number === 1) return (number + " is odd");
        return checkNumber(number - 2);
    }
    console.log(checkNumber(5));
    console.log(checkNumber(10));
    console.log(checkNumber(13333));
</script>


Output:

1 is odd
0 is even
1 is odd


Last Updated : 26 Jul, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads