Array Sum
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
Algorithm Flow

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
function arraySum(nums: number[]): number {
var sum = 0;
for (var i = 0; i < nums.length; i++) {
sum += nums[i];
}
return sum;
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
