10 Examples for Recursion in JavaScript

1) Countdown from any number to 0

The program starts the countdown from n to 0 while printing a number every second. The recursive call “countDown(count-1)” is made inside callback function of the setTimeout() function. The base condition ensures that the countdown ends once the count is equal to 0.

function countDown(count){
  console.log(count);
  if(count==0){
    return;
  }
  setTimeout(()=>{countDown(count-1)},1000);
}

countDown(5);
// 5 4 3 2 1 0

2) Sum of digits of a number

The last digit of the num is added with a recursive call of “digitSum(num/10)” and the recursive call is terminated once the num variable is 0.

var number = 3467;

function digitSum(num){
  if(num==0){
    return num;
  }
  return num%10 + digitSum(Math.floor(num/10));
}

digitSum(number); // 20

3) Flattening of Array

In this example, the array with nested subarrays at n levels is flattened.

  1. if element at the index is an array, recursive call to flatten the subarray “flattenArray(arr[i],0)” is made.
  2. if the element is a number, there is no need to flatten hence element is directly pushed into the result array.
  3. After both cases, a recursive call to flatten the next element of the array “flattenArray(arr,i+1)” is made.
var arr = [2,[3,12,24],17,[54,[24,3],8]];
var result=[];

function flattenArray(arr,i){
  if(i>=arr.length){
    return;
  }
  if(Array.isArray(arr[i])){
    flattenArray(arr[i],0);
  }
  else{
    result.push(arr[i]);
  }
  flattenArray(arr,i+1);
}

flattenArray(arr,0);

console.log(result);
// [2, 3, 12, 24, 17, 54, 24, 3, 8]

4) Factorial of a number

The factorial of a number “factorial(i)” is broken down into “i*factorial(i-1)“. Every recursive call reaches the base condition where i <= 1 which returns 1.

function factorial(i) {
  if (i > 1) { 
    return factorial(i - 1) * i;
  }
  return 1;
}

console.log(factorial(5));
// 120

5) Fibonacci series

The Fibonacci number of n is calculated by adding the Fibonacci numbers of n-1 and n-2. Additionally, base conditions f(0) =0, f(1)=1 and f(2)=1 are included.

function findFib(n){
  if(n<=0){
    return 0;
  }
  else if(n<3){
    return 1;
  }
 return findFib(n-1) + findFib(n-2);
}

console.log(findFib(5));
// 5

console.log(findFib(9));
// 34

6) Print elements of an array

The current array element “arr[i]” is printed and recursive call to print next element “printArray(arr, i + 1)” is made. Once all elements of the array are printed and “i” variable exceeds the array length, the function call is returned to avoid infinite recursion.

var arr = [2, 12, 34, 54, 41];

function printArray(arr, i) {
  if (i >= arr.length) {
    return;
  }
  console.log(`Element at index ${i} is ${arr[i]}`);
  printArray(arr, i + 1);
}
printArray(arr, 0);

// Element at index 0 is 2
// Element at index 1 is 12
// Element at index 2 is 34
// Element at index 3 is 54
// Element at index 4 is 41

7) Total sum of an array

The total sum of an array is calculated from the addition of the current array element arr[i] with a recursive call of the following index “arraySum(i+1,arr)“. The base condition “i >= arr.length” ensures termination beyond the last index of the array.

var arr = [2, 12, 34, 54, 41];

function arraySum(i,arr) {
  if (i >= arr.length) {
    return 0;
  }
  return arr[i] + arraySum(i+1,arr);
}

console.log(arraySum(0,arr));
// 143

8) Find an element using Binary Search

The recurse approach for binary search in a sorted array follows the steps:

  1. if low> high, the element is not found hence -1 is returned.
  2. else if search element x == arr[mid], the element is found, hence mid is returned.
  3. else if x > arr[mid], search element is expected to be present between mid+1 and high index.
  4. else search element is expected to be present between low and mid-1.
var arr=[2, 16, 23, 33, 41, 51, 73];
var x = 33;

function findElement(arr,x,low,high){
  var mid=low+high/2;
  if(low > high){
    return -1;
  }
  else{
    if(x==arr[mid]){
      return mid;
    }
    else if(x > arr[mid]){
      return findElement(arr,x,mid+1,high);
    }
    else{
      return findElement(arr,x,low,mid-1);
    }
  }
}

function searchElement(arr,x){
  const index = findElement(arr,x,0,arr.length-1);
  console.log(`${x} is found at index ${index}`);
}

searchElement(arr,x);
// 33 is found at index 3

9) Sum of nested objects

The “obj.value” is added with recursive call “findSum(obj.children)” and base condition “obj.children == null” ensures termination when no children object is present.

var myObject = {
    name: "object1",
    value: 3,
    children: {
      name: "object2",
      value: 5,
      children: null
    }
}

function findSum(obj){
  if(obj.children == null){
    return obj.value;
  }  
  return obj.value + findSum(obj.children);   
}

findSum(myObject);
// 8

10) Print all factors of a number

If the number is divided by a variable without any remainder then it will be printed. The recursive call “printFactors(number, fact+1)” ensures every factor between 1 to number/2 is printed.

function printFactors(number, fact){
  if(number/fact < 2){
    console.log(number)
    return;
  }  
  if(number%fact == 0){
    console.log(fact); 
  }
  return printFactors(number, fact+1);
}

function findFactors(number){
  printFactors(number,1);
}

findFactors(20);
// 1 
// 2
// 4
// 5
// 10
// 20