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) {

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

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);

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


Did you find this article valuable?

Support Anurag Kumar by becoming a sponsor. Any amount is appreciated!