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.
Example: The function `sumOfEvenNumbers` calculates the sum of even numbers in an array using a loop and conditional statements.
Javascript
function sumOfEvenNumbers(arr) { let sum = 0; for (let i = 0; i < arr.length; i++) { if (arr[i] % 2 === 0) { sum += arr[i]; } } return sum; } const numbers = [1, 2, 3, 4, 5]; const evenSum = sumOfEvenNumbers(numbers); console.log( "Sum of even numbers:" , evenSum); |
Output
Sum of even numbers: 6
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