Given an array of numbers, find the sum of all even numbers.
Code Playground
JavaScript (V8)
Loading...
Console Output
// Output will appear here...
// For React: ReactDOM.createRoot(rootElement).render(<App />);
// For React: ReactDOM.createRoot(rootElement).render(<App />);
Recommended Answer
Approach 1: filter() and reduce() (Functional)
This is a modern and expressive way to solve the problem.
function sumEvenNumbers(numbers) {
return numbers
.filter(num => num % 2 === 0) // Keep only even numbers
.reduce((sum, currentNum) => sum + currentNum, 0); // Sum them up
}
console.log(sumEvenNumbers([1, 2, 3, 4, 5, 6])); // 12Approach 2: Simple Loop
This approach is straightforward and can be slightly more performant on very large arrays as it only iterates once.
function sumEvenNumbersLoop(numbers) {
let sum = 0;
for (const num of numbers) {
if (num % 2 === 0) {
sum += num;
}
}
return sum;
}
console.log(sumEvenNumbersLoop([1, 2, 3, 4, 5, 6])); // 12