Start at 0
Accumulator
Zero is the additive identity.
Summing an array means visiting every element once and adding it to a running total (the accumulator pattern). Example: [1, 2, 3, 4, 5] → 15. Empty arrays sum to 0; negatives are allowed. This tutorial covers a manual loop, user input, a live preview, worked JavaScript examples, edge cases, and complexity.
Accumulator
Zero is the additive identity.
total += x
Visit each element exactly once.
Edge case
No elements means the total stays 0.
Same loop
They simply reduce the total.
Try 1,2,3,4,5
Compute a custom array instantly.
Interview tip
Show the loop; use reduce later.
Summing an array is the simplest one-pass array problem: keep a running total and add every value. With [1, 2, 3, 4, 5] the total climbs 0 → 1 → 3 → 6 → 10 → 15.
Interviews want the manual accumulator so you prove you understand traversal. In real JavaScript you can later switch to arr.reduce((a, b) => a + b, 0) without changing the idea.
It is the foundation for averages, prefix sums, and many later array scans (max, min, product).
total starts at 0.
O(n) time, O(1) space.
Natural with this pattern.
Same scan, different keep.
In short: total = 0, then total += value for every element.
Given an array of numbers, return the sum of all elements.
# [1, 2, 3, 4, 5] -> 15
# [10, -2, 7] -> 15
# [] -> 0 | Item | Type | Description |
|---|---|---|
arr | number[] | Values to add (may be empty). |
| Return | int | Sum of all elements (0 if empty). |
total | int | Running accumulator. |
function sumArray(arr) {
let total = 0;
for (const value of arr) {
total += value;
}
return total;
} | Method | Idea | Notes |
|---|---|---|
| Manual loop | total += value | Interview default |
| Built-in reduce | arr.reduce((a, b) => a + b, 0) | Best in production |
| Index loop | for (let i = 0; i < arr.length; i++) | Same O(n); useful with indices |
| Goal | Pattern |
|---|---|
| Init | total = 0 |
| Add | total += value |
| For-each | for (const value of arr) |
| By index | for (let i = 0; i < arr.length; i++) total += arr[i] |
| Built-in | arr.reduce((a, b) => a + b, 0) |
| Empty | [] → 0 |
Same result — different packaging.
total += xClearest interview answer
arr.reduce(...)Idiomatic production JavaScript
arr[i]When you also need positions
keep bestSame pass, different update
Reach for an array sum whenever you need a one-pass total.
First array traversal after variables.
Sum then divide by length.
Running totals unlock range queries.
Read n values, then total them.
Product starts at 1, not 0.
Key benefit: one pattern — start at 0, add everything — that transfers to almost every array scan.
Enter integers separated by commas or spaces and compute the sum instantly.
Three complete JavaScript programs — sum a fixed array, read user-style input, and show a running total with negatives. Click View Output to reveal sample console results.
The classic accumulator on a hard-coded array.
Classic example: [1, 2, 3, 4, 5] → 15.
function sumArray(arr) {
let total = 0;
for (const value of arr) {
total += value;
}
return total;
}
const array = [1, 2, 3, 4, 5];
console.log(`Sum of the array elements: ${sumArray(array)}`); total starts at 0 and climbs as each value is added: 1, then 3, 6, 10, and finally 15.
Same helper, values come from the user.
Reads n and then n numbers from the user. Rejects a negative length.
function sumArray(arr) {
let total = 0;
for (const value of arr) {
total += value;
}
return total;
}
// Simulated input (edit these values)
const n = 5;
const arr = [1, 2, 3, 4, 5];
if (n < 0) {
throw new Error("n must be nonnegative.");
}
console.log(`Sum of the array elements: ${sumArray(arr)}`); Build the array first, then reuse the same sumArray helper. Keeping input and summing separate makes testing easier.
Print the accumulator after each step so you can see negatives reduce the total.
const arr = [10, -2, 7];
let total = 0;
console.log("Running total:");
for (const value of arr) {
total += value;
const signed = value >= 0 ? `+${value}` : String(value);
console.log(` after ${signed}: ${total}`);
}
console.log(`Final sum: ${total}`); Negatives are not special-cased — addition handles them. Tracing the running total is a great whiteboard habit.
Additive identity for an empty start.
for (const value of arr)
Fold the next element into the sum.
After the loop, total is the answer.
Watch the accumulator climb from 0 to 15.
| Step | value | total after |
|---|---|---|
| start | — | 0 |
| 1 | 1 | 1 |
| 2 | 2 | 3 |
| 3 | 3 | 6 |
| 4 | 4 | 10 |
| 5 | 5 | 15 |
Same table works for [10, -2, 7]: 0 → 10 → 8 → 15.
Where array sums show up beyond the interview prompt.
First array traversal drill.
Example: sumArray([1,2,3]).
Sum then divide by n.
Example: average tutorials.
Cart totals, scores, balances.
Example: add line items.
Store running totals for ranges.
Example: range queries.
Checksum-style quick totals.
Example: live preview.
Same pass, keep the best.
Example: related CTA.
Pro Tip: say “accumulator starts at zero” before you write the loop.
Why the one-pass accumulator is the right first approach.
One variable, one loop, one update.
You must look at every element anyway.
Only the accumulator — O(1) space.
Empty arrays and negatives need no special cases.
Pro Tip: mention arr.reduce((a, b) => a + b, 0) as a production shortcut after you show the manual loop.
Small habits that keep sum solutions interview-ready.
Never seed with arr[0] for summing.
Do not nest or sort first.
Guard negative n when reading length.
Write the running total for small arrays.
Mention it after the manual solution.
Pro Tip: sanity-check [], [1,2,3,4,5], and [10,-2,7] — if those three work, you are solid.
Mistakes that commonly break sum-of-array programs.
That pattern is for max/min, not sum.
→ Always start sum at 0.
Crashing when n = 0.
→ Empty sum is 0 with this pattern.
Treating them as invalid.
→ Addition already handles them.
Unnecessary O(n log n) work.
→ One linear pass is enough.
Unvalidated input breaks int conversion.
→ Validate before summing.
Handle these before claiming the sum is complete.
Result remains 0.
They reduce the total naturally.
[7] → 7.
Handle non-numeric values before summing.
Raise or re-prompt.
Adding 0 leaves total unchanged.
Handy follow-ups interviewers sometimes ask.
Try these variations to lock in the pattern.
arr.reduce((a, b) => a + b, 0) is fine after you can write the loop.Quick Takeaway: total = 0; for each value, total += value.
| Approach | Time | Extra space |
|---|---|---|
| Single pass | O(n) | O(1) |
| Built-in reduce | O(n) | O(1) |
| Sort then add | O(n log n) | varies |
You must read every element, so linear time is optimal for an unsorted array.
Summing an array is the accumulator pattern: start at 0, add every element once, return the total. Empty arrays stay 0; negatives just subtract.
Practice the three examples above, then continue to finding the maximum of an array.
total = 0; total += each value.
Master the accumulator pattern for every later scan.
total = 0
Inittotal += x
Loopsum is 0
Edgejust subtract
InputO(n) / O(1)
AnalysisThe “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.
Learn how to find the largest element with a single linear scan.
9 people found this page helpful