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:
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 Step 2. Initializing a prompt that can be used to enter the ussd code
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: Output 2: If a user entered the correct USSD Code. Output 3: If the user entered a number that is not from 1 - 4 then it will alert the user "wrong input" Output 4: After the warning alert then the recursive function will invoke the parent function to execute again
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();
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.