Code Logo

Array Sum

Published at24 Jul 2026
TypeScript Data Structures Easy 0 views
Like0

Write a TypeScript function that takes an array of numbers and returns their sum. Use a for loop to iterate through the array and accumulate the total.

Initialize a sum variable to 0. Loop through each element and add it to sum. Return the total after the loop completes. This demonstrates basic array iteration and accumulation.

Edge cases include empty arrays (return 0), single-element arrays, arrays with negative numbers, and arrays with zeros.

Array summation is a fundamental operation in programming. The accumulator pattern (sum += element) is used across countless algorithms. TypeScript's type annotations ensure type safety: the parameter type number[] guarantees all elements are numbers.

The for loop provides explicit control over iteration, allowing the programmer to start, end, and step through the array as needed. This is the most widely supported loop construct across all JavaScript/TypeScript environments.

Edge cases include empty arrays (returns 0), single-element arrays, negative numbers that cancel out, and large arrays where the sum may exceed typical integer ranges.

Array summation is a fundamental operation in programming. The accumulator pattern (sum += element) is used across countless algorithms. TypeScript's type annotations ensure type safety: the parameter type number[] guarantees all elements are numbers.

The for loop provides explicit control over iteration, allowing the programmer to start, end, and step through the array as needed. This is the most widely supported loop construct across all JavaScript/TypeScript environments.

Edge cases include empty arrays (returns 0), single-element arrays, negative numbers that cancel out, and large arrays where the sum may exceed typical integer ranges. The accumulator variable is initialized to 0 to handle the empty array case correctly.

Example Input & Output

Example 1
Input
[10,20,30]
Output
60
Example 2
Input
[]
Output
0
Example 3
Input
[1,2,3,4,5]
Output
15
Example 4
Input
[-5,5]
Output
0
Example 5
Input
[7]
Output
7

Algorithm Flow

Recommendation Algorithm Flow for Array Sum
Recommendation Algorithm Flow for Array Sum

Solution Approach

Initialize sum = 0. Use a for loop from 0 to nums.length - 1. Add each element to sum. Return sum.

The time complexity is O(n). Space complexity is O(1).

Best Answers

typescript - Approach 1
function arraySum(nums: number[]): number {
    var sum = 0;
    for (var i = 0; i < nums.length; i++) {
        sum += nums[i];
    }
    return sum;
}