Sum of Even Numbers of an Array using Recursive Approach

This method solves the problem by using recursion. It defines a function that accepts three parameters: the array, the current index, and the sum of the total. After checking that the array has ended in the base case, the function calls itself recursively with the next element and, if the current number is even, changes the total.

Example: Recursive function `sumOfEvenNumbers` computes the sum of even numbers in an array. It recursively processes the array, adding even numbers to the sum. The base case returns 0 if the array is empty.

Javascript




function sumOfEvenNumbers(arr) {
    // Base case: If the array is empty, return 0.
    if (arr.length === 0) {
        return 0;
    }
 
 
    const firstElement = arr[0];
    const restOfArray = arr.slice(1);
 
    if (firstElement % 2 === 0) {
        return firstElement +
            sumOfEvenNumbers(restOfArray);
    } else {
 
        return sumOfEvenNumbers(restOfArray);
    }
}
 
const numbers = [1, 2, 3, 4, 5, 6];
const evenSum = sumOfEvenNumbers(numbers);
console.log("Sum of even numbers:", evenSum);


Output

Sum of even numbers: 12

JavaScript Program to Find Sum of Even Numbers of an Array

In JavaScript, working with arrays is a basic operation. We have to sum all the even numbers present in the array. We can check the number if it is even or not by the use of the % operator.

These are the following ways to find the sum of Even numbers in an Array:

Table of Content

  • Iterative Approach
  • Using filter() and reduce() methods
  • Recursive Approach
  • Using forEach Loop

Similar Reads

Sum of Even Numbers of an Array using Iterative Approach

This method iterates through each element in the array and checks if it’s even. If it is, the element is added to a running total variable, which stores the cumulative sum of all even numbers encountered so far....

Sum of Even Numbers of an Array using filter() and reduce() methods

...

Sum of Even Numbers of an Array using Recursive Approach

This method provides a simpler answer by using built-in array functions. By using the filter method, an array is created that is limited to the even elements present in the original array. The filtered array is then iterated by using the reduce method, which adds each element to the sum....

Sum of Even Numbers of an Array using Using forEach Loop

...