Practical use of Recursion in javascript

Recursion is the practice of repeating a process until when an expected output is met or the determination of a succession of elements (such as numbers or functions) by operation on one or more preceding elements. In Javascript, a function that calls itself is known as recursion.

Example: image.png

Now lets play with some functions to get the full use of recursion. I am going to walk you through on how to build a USSD for bank and we will be using recursion when and where necessary.

Step 1. Declare a function image.png Step 2. Initializing a prompt that can be used to enter the ussd code image.png

here if a user entered a ussd code that is not *901# then the user will get an alert that says wrong entry. Then the recursion function "accessBankUSSD( )" will invoke the parent function to repeat itself until the user input the right ussd code.

Output 1: Screenshot (174).png Output 2: If a user entered the correct USSD Code. Screenshot (175).png Output 3: If the user entered a number that is not from 1 - 4 then it will alert the user "wrong input" Screenshot (177).png Output 4: After the warning alert then the recursive function will invoke the parent function to execute again Screenshot (179).png

const accessBankUSSD = () => {
//declaration of a variable for user input
  let ussd = prompt("Enter Access bank USSD code");
 // A conditional statement for a code the user must  enter
 if(ussd == "*901#") {
   let option = prompt(`Access Bank
       1>Check Balance
       2>Transfers
       3>Airtime
       4>Other Services`);
       // if the user entered a number that is not between 1-4 it will alert "wrong input" then recursion takes place
       if(option == 1 || option == 2 || option == 3 || option == 4) {
         alert("Sorry our app is undergoing maintenance")
       } 
       else{
         alert("wrong input");

         //Recursion
         accessBankUSSD();
       }
  } 
  else{
    alert("wrong input");
    // Recursion
    accessBankUSSD();
  }
};
accessBankUSSD();

Live Demo

Conclusion

  • Recursion is when a function calls itself until someone stops it.

  • It can be used instead of a loop.

  • If no one stops it, it'll recurse forever and crash your program.

  • Recursion helps in writing lesser code especially when iterating.