How to use Recursion In Javascript

We could define recursion formally in simple words, that is, a function calling itself again and again until it doesn’t have left with it anymore.

Example: This example shows the above-explained approach.

Javascript
// Creating array
let arr = [4, 8, 7, 13, 12];

// Function to find the sum of the array using recursion
function sumArray(arr, index) {
    if (index === arr.length) {
        return 0;
    }
    return arr[index] + sumArray(arr, index + 1);
}

console.log("Sum is " + sumArray(arr, 0));

Output
Sum is 44

How to find the sum of all elements of a given array in JavaScript ?

Finding the sum of all elements in a given array in JavaScript involves iterating through the array and accumulating the values using a loop or array method like reduce(). This process yields the total sum of all array elements.

Below all the approaches are described with a proper example:

Table of Content

  • Using for loop
  • Using forEach() Method
  • Using reduce() Method
  • Using Recursion
  • Using Lodash _.sum() Method

Similar Reads

Using for loop

We are simply going to iterate over all the elements of the array using a Javascript for loop to find the sum....

Using forEach() Method

We are going to use the Javascript forEach() method of the array to calculate the sum....

Using reduce() Method

We are going to use the Javascript reduce() method to find the sum of the array....

Using Recursion

We could define recursion formally in simple words, that is, a function calling itself again and again until it doesn’t have left with it anymore....

Using Lodash _.sum() Method

In this approach, we are using the Lodash _.sum() method for getting the sum of all element of an array....

Contact Us