Recursion (JavaScript) Day 1

Recursion (JavaScript) Day 1

What is Recursion and Why Recursion is necessary?

Recursion is an occurrence of the same event time and again till the time, it reaches its endpoint.

Let's understand Recursion through a journey from Delhi to Ladakh and Back to Delhi.

Recursion.png

In the above diagram Step is a Vehicle to drive you from one place to another. Step 1 is Delhi and Step 5 is Ladakh. In between 3 checkpoints. So let's start with the Recursive Journey. You started from Step 1 to Step 2 and so on telling the Step vehicle to make you reach Ladakh as soon as you reached Ladakh you hit the base condition. Let's understand what is base condition.

function main() {
    step(["Delhi","Kulu","Ladakh"]);
} 

function step(nextDest) {
  // Base Condition
  if(nextDest.length && nextDest[0]=="Ladakh") {
    console.log("Reached Destination ->" + nextDest[0]);
    return;
  }
  // Travel Begins
  let currDest = nextDest[0];
  console.log("Towards Destination ->" + currDest);
  // Recursion 
  step(nextDest.splice(1));
  // Back to Home
  console.log('Back to Home ->' + currDest);
}

main();

Recursion-example.png

Let's Practice Simple Problem to Print Numbers in Ascending and Descending Order using Recursion?

function main() {
    ascRecurion(10);
    descRecurion(10);
}

//Print Number in Increasing Order using Recursion

function ascRecurion(n) {
    // Base Case
    if(n==0){ 
        console.log(n);
        return;
    }
    // Recursive Case
    ascRecurion(n-1);
    // Post Recursion Print Ascending Order
    console.log(n);
}

//Print Number in Descending Order using Recursion
function descRecurion(n) {
    // Base Case
    if(n==0){ 
        console.log(n);
        return;
    }
    // Pre Recursion Print Descending Order
    console.log(n);
    // Recursive Case
    descRecurion(n-1); 
}

main();

Please console.log(result) in the comments below and we will come up with day 2;

Did you find this article valuable?

Support ANURAG SARAN by becoming a sponsor. Any amount is appreciated!