Open In App

How to Understand Recursion in JavaScript ?

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:

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.




<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.




<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

Article Tags :