Sum Even Numbers
Write a TypeScript function that takes an array of integers and returns the sum of all even numbers. Use the modulo operator to check if a number is even.
Loop through the array with a for loop. Check each number with num % 2 === 0. Add even numbers to an accumulator. Return the total sum.
Edge cases include empty arrays (return 0), arrays with no even numbers (return 0), and negative even numbers.
Summing even numbers teaches array iteration and the modulo operator for divisibility checking. TypeScript's type annotations help catch type errors at compile time. The for loop pattern with a numeric index is the most compatible approach across different TypeScript compilation targets.
TypeScript arrays are typed containers. The annotation `nums: number[]` ensures only numbers can be passed to the function. The modulo operator % works the same as in JavaScript, returning the remainder of division.
The standard for loop with index variable is the most compatible pattern across all TypeScript compilation targets, avoiding issues with newer iteration constructs that may not be supported in older ECMAScript versions.
The modulo operation n % 2 checks divisibility by 2. When the result is 0, the number is even. This works for both positive and negative integers, making it reliable for all integer inputs.Example Input & Output
Algorithm Flow

Solution Approach
Initialize sum = 0. Loop through the array with a standard for loop. If nums[i] % 2 === 0, add to sum. Return sum after the loop.
The time complexity is O(n). Space complexity is O(1).
Best Answers
function sumEven(nums: number[]): number {
var sum = 0;
for (var i = 0; i < nums.length; i++) {
if (nums[i] % 2 === 0) sum += nums[i];
}
return sum;
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
