Home JavaScript Interview Programs Sum of Array JavaScript Sum of Array Program Definition
What Is the Sum of an Array? The sum of an array is the result of adding every element once. This is the classic accumulator pattern: start at 0, then total += value for each item.
sum(arr) = arr[0] + arr[1] + ... + arr[n-1]
Example: [1, 2, 3, 4, 5]
0 → 1 → 3 → 6 → 10 → 15
Empty array → 0 Array Running total Sum [1, 2, 3, 4, 5]1, 3, 6, 10, 15 15[10, -2, 7]10, 8, 15 15[](no steps) 0
Approach
How to Find the Sum of an Array in JavaScript Four clear steps — one pass is enough.
Set total = 0. Visit every element with a for...of loop or an index loop. Add each value: total += value. Return total after the loop ends. Method Idea Time Best for for...ofAccumulator over each value O(n)Interviews, clearest logic Index for loop total += arr[i]O(n)When you need the index reducearr.reduce((a, b) => a + b, 0)O(n)Production code
Pseudocode function SumArray(arr):
total = 0
for each value in arr:
total = total + value
return total Reference
Cheat Sheet Keep these facts handy while writing the program.
Topic Detail Start total = 0Step total += valueEmpty array Sum is 0 Negatives Allowed; they reduce the total Order Does not matter for ordinary numbers Classic check [1, 2, 3, 4, 5] → 15
Try it
Live Preview Enter integers separated by commas or spaces to see the running total and final sum.
Code
JavaScript Programs Start with a fixed array and a simple helper. Then parse values from a string, and finish by tracing a running total with negatives. Each example has a Try it Yourself editor.
1. Fixed array 2. Parsed input 3. Running total Example 1 — Sum of a Fixed Array Use a for...of loop to add every element into an accumulator.
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)); Sum of the array elements: 15 How It Works total starts at 0.for...of visits 1, 2, 3, 4, then 5.Each visit does total += value. The running values are 1, 3, 6, 10, then 15. Return the final total after the loop. Example 2 — Sum with Parsed Input Split a string of numbers, then reuse the same summing helper.
function parseNumbers(text) {
const t = String(text || "").trim();
if (!t) {
return [];
}
const parts = t.split(/[\s,]+/).filter(Boolean);
const arr = [];
for (const part of parts) {
const value = Number(part);
if (!Number.isFinite(value)) {
return null;
}
arr.push(value);
}
return arr;
}
function sumArray(arr) {
let total = 0;
for (const value of arr) {
total += value;
}
return total;
}
const rawInput = "10 -2 7";
const arr = parseNumbers(rawInput);
if (!arr) {
console.log("Invalid input");
} else {
console.log("Array: " + arr.join(" "));
console.log("Sum of the array elements: " + sumArray(arr));
} How It Works parseNumbers splits on spaces or commas and builds an array.Invalid tokens return null so callers can reject bad input. An empty string becomes [], and the sum is 0. Call sumArray — parsing and summing stay separate. Edit rawInput in the Try it Yourself editor to try other values. Example 3 — Running Total with Negatives Print the accumulator after each step so negatives are easy to see.
const arr = [10, -2, 7];
let total = 0;
console.log("Running total:");
for (const value of arr) {
total += value;
const sign = value >= 0 ? "+" : "";
console.log(" after " + sign + value + ": " + total);
}
console.log("Final sum: " + total); Running total:
after +10: 10
after -2: 8
after +7: 15
Final sum: 15 How It Works Start at 0, then add 10 → 10. Add -2 → 8 (no special case for negatives). Add 7 → 15. A simple sign prefix shows each added value clearly. Tracing the running total is a strong whiteboard habit. Edge Cases & Pitfalls Check these before calling the solution done.
Empty Sum is 0 An empty array never enters the loop, so the accumulator stays at 0.
Negatives Just add them Do not take absolute values unless the problem asks for that.
Precision Safe integers For very large totals, stay within Number.MAX_SAFE_INTEGER or use BigInt if needed.
Nullish Guard bad arrays In real code, check for null/undefined before looping. Interviews often assume a valid array.
Analysis
Time and Space Complexity Program Time Extra space for...of / index loopO(n)O(1)Parse + sum O(n)O(n) for the arrayRunning-total trace O(n)O(1)
You must look at every element at least once, so O(n) is optimal for the general case.
Remember
Key Takeaways Pattern: accumulator starts at 0, then adds each element once.
Loop: for (const value of arr) total += value;
Empty: no iterations → sum stays 0.
Test set: [1,2,3,4,5] → 15; [10,-2,7] → 15; [] → 0.
One line: start at zero, add every element once, return the total.
Frequently Asked Questions How do you find the sum of an array in JavaScript? Start with total = 0, then loop through the array and add each element with total += value.
Why does the total start at 0? Zero is the additive identity. Starting there makes the final total equal the sum of all elements, including the empty-array case.
Can the array contain negative numbers? Yes. The same loop works; negatives reduce the running total.
Should I use reduce or a loop? Prefer a loop in interviews to show the accumulator. In production code, arr.reduce((a, b) => a + b, 0) is fine.
What is the time complexity? O(n) time and O(1) extra space for a single pass over n elements.
How do I try the examples interactively? Use the Try it Yourself links under each code sample — they open an in-browser editor with the same logic so you can edit the input and Run.
About the author Developer, cloud engineer, and technical writer
I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.
13 people found this page helpful
Helpful Share Copy link Suggestion