Code Logo

Sum Even Numbers

Published at24 Jul 2026
TypeScript Data Structures Easy 2 views
Like0

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

Example 1
Input
[2,4,6]
Output
12
Example 2
Input
[1,2,3,4,5]
Output
6
Example 3
Input
[]
Output
0
Example 4
Input
[-2,-4,1]
Output
-6
Example 5
Input
[1,3,5]
Output
0

Algorithm Flow

Recommendation Algorithm Flow for Sum Even Numbers
Recommendation Algorithm Flow for Sum Even Numbers

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

typescript - Approach 1
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;
}