Sum of Even Numbers of an Array using Using forEach Loop
This method uses forEach to iterate through the array, providing an alternative to the normal loop. It keeps readability and efficiency while providing a slightly more simple solution.
Example: The `sumOfEvenNumbers` function calculates the sum of even numbers in an array using a forEach loop. It iterates through the array, adding each even number to the sum. The example demonstrates its usage by finding the sum of even numbers in an array and printing the result.
Javascript
function sumOfEvenNumbers(arr) { let sum = 0; arr.forEach(num => { // Check if the current element is even. if (num % 2 === 0) { // If the current element // is even, add it to the sum. sum += num; } }); // Return the total sum of even numbers. return sum; } 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