Find Sum of Array in JavaScript
What you’ll learn
- The simplest way to compute a total using an accumulator (
sum += arr[i]). - How to write a clean C program for a fixed array and for user input.
- Common edge cases: empty input, negatives, and overflow.
Overview
To find the sum of an array, you visit each element exactly once and keep adding it to a running total. This is one of the most common patterns in programming, and it teaches you how loops and arrays work together.
Two programs
Example 1 sums {1,2,3,4,5}. Example 2 reads n and then n integers from the user.
Live preview
Paste numbers like 10, -2, 7 and see the computed sum instantly.
Safe sum type
JavaScript uses Number; for very large integers, switch to BigInt if exact precision matters.
Live preview
Enter integers separated by commas or spaces (example: 1 2 3 or 1, 2, 3).
Algorithm
Goal: compute a[0] + a[1] + ... + a[n-1].
Initialize
Set sum = 0.
Loop through the array
For every index i from 0 to n-1, add a[i] into sum.
Return or print
After the loop, sum is the total.
📜 Pseudocode
function arraySum(a, n):
sum ← 0
for i from 0 to n-1:
sum ← sum + a[i]
return sumSum of a fixed array
This matches the classic example: {1,2,3,4,5} sums to 15.
function sumArray(arr) {
let sum = 0;
for (let i = 0; i < arr.length; i++) {
sum += arr[i];
}
return sum;
}
const array = [1, 2, 3, 4, 5];
const sum = sumArray(array);
console.log("Sum of the array elements: " + sum);Sum of an array (user input)
Reads n, then reads n integers. Uses long long for the running total.
function sumArray(arr) {
let sum = 0;
for (let i = 0; i < arr.length; i++) {
sum += arr[i];
}
return sum;
}
const input = "10 -2 7";
const arr = input
.trim()
.split(/\s+/)
.map(Number)
.filter((v) => Number.isFinite(v));
console.log("Array:", arr.join(" "));
console.log("Sum of the array elements: " + sumArray(arr));❓ FAQ
🔄 Input / output examples
| Array | Sum |
|---|---|
{1,2,3,4,5} | 15 |
{10,-2,7} | 15 |
{} (n=0) | 0 |
Edge cases and pitfalls
Summing is simple, but these details keep your solution correct in interviews.
Empty array
The sum of zero numbers is 0. The loop runs zero times and sum stays 0.
Total may exceed int
If numbers are large (or there are many), JavaScript Number can lose integer precision. Use BigInt when exact huge integer sums are required.
Invalid reads
Always validate parsed values from strings so invalid tokens do not silently corrupt the sum.
⏱️ Time and space complexity
| Approach | Time | Extra space |
|---|---|---|
| One loop through n elements | O(n) | O(1) |
Summary
- Pattern:
sum = 0, thensum += arr[i]for each element. - Use: choose
long longfor safer totals. - Complexity:
O(n)time,O(1)extra space.
The “sum of an array” program is the simplest example of the accumulator pattern: start with sum = 0, then add each element once. This idea appears everywhere: totals, averages, dot products, and prefix sums.
9 people found this page helpful
