Simple examples of Recursion in JavaScript
What is Recursion - > Recursion is when a function calls itself. For each call it creates a stack. like push and pop in JavaScript. First it will keep pushing in the stack with new parameters each time like n-1 . then it will pop one by one and return the result to the parent function in the stack.
function printnum(n) {
// Write a condition to end the infinite loop, so end the recursion when n=0
if (n == 0) {
return;
}
// keep calling to function inside another function by passing parameter 1 less each time.
printnum(n - 1);
// when recursion completes when n==0 , it will start logging value of n from 1 to 100
console.log(n);
}
printnum(100);
function isEven(n) {
n = Math.abs(n); // convert n to positive number
if (n == 0) return true; // when n ==0 it is even number
if (n == 1) return false; // when n==1 it is odd
// To know if number is even we just have to keep subtracting number 2 from
// the given number until the value of n reaches either 1 or 0
return isEven(n - 2);
}
console.log(isEven(50));
console.log(isEven(75));
console.log(isEven(-1));
function getFactorial(n){
if(n==1)return n; // return from loop when n reaches 1
return n*getFactorial(n-1); with each return keep multiplying n by n-1
}
console.log(getFactorial(5));