Find Sum of Array in JavaScript

Beginner
⏱️ 8 min read
📚 Updated: Aug 2026
🎯 3 Code Examples
🚀 Live Preview
Arrays

What You’ll Learn

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.

Start at 0

Accumulator

Zero is the additive identity.

One Pass

total += x

Visit each element exactly once.

Empty = 0

Edge case

No elements means the total stays 0.

Negatives OK

Same loop

They simply reduce the total.

Live Preview

Try 1,2,3,4,5

Compute a custom array instantly.

Loop vs reduce

Interview tip

Show the loop; use reduce later.

Introduction

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.

Why it matters?

It is the foundation for averages, prefix sums, and many later array scans (max, min, product).

Key Highlights

Accumulator

total starts at 0.

Single Pass

O(n) time, O(1) space.

Empty = 0

Natural with this pattern.

Next: Max

Same scan, different keep.

In short: total = 0, then total += value for every element.

📝 Problem & Approach

Given an array of numbers, return the sum of all elements.

JavaScript
# [1, 2, 3, 4, 5] -> 15
# [10, -2, 7]     -> 15
# []              -> 0

Inputs & Outputs

ItemTypeDescription
arrnumber[]Values to add (may be empty).
ReturnintSum of all elements (0 if empty).
totalintRunning accumulator.

Minimal workflow

Pseudocode
function sumArray(arr) {
  let total = 0;
  for (const value of arr) {
    total += value;
  }
  return total;
}

Method comparison

MethodIdeaNotes
Manual looptotal += valueInterview default
Built-in reducearr.reduce((a, b) => a + b, 0)Best in production
Index loopfor (let i = 0; i < arr.length; i++)Same O(n); useful with indices

⚡ Quick Reference

GoalPattern
Inittotal = 0
Addtotal += value
For-eachfor (const value of arr)
By indexfor (let i = 0; i < arr.length; i++) total += arr[i]
Built-inarr.reduce((a, b) => a + b, 0)
Empty[]0

📋 Loop vs reduce vs Index

Same result — different packaging.

Accumulator
total += x

Clearest interview answer

Built-in
arr.reduce(...)

Idiomatic production JavaScript

Index
arr[i]

When you also need positions

vs max
keep best

Same pass, different update

Context

When This Problem Shows Up

Reach for an array sum whenever you need a one-pass total.

  1. Interview warm-ups

    First array traversal after variables.

  2. Averages

    Sum then divide by length.

  3. Prefix sums

    Running totals unlock range queries.

  4. Input parsing

    Read n values, then total them.

  5. Not for products

    Product starts at 1, not 0.

Key benefit: one pattern — start at 0, add everything — that transfers to almost every array scan.

🔮 Live Preview

Enter integers separated by commas or spaces and compute the sum instantly.

Integers only (safe integer range), up to 2000 values. Empty input sums to 0.

Live result
Press “Compute sum”.

Examples Gallery

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.

📚 Getting Started

The classic accumulator on a hard-coded array.

Example 1 — Sum of a Fixed Array

Classic example: [1, 2, 3, 4, 5] → 15.

JavaScript
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)}`);

How It Works

total starts at 0 and climbs as each value is added: 1, then 3, 6, 10, and finally 15.

⚡ Reading Input

Same helper, values come from the user.

Example 2 — Sum of an Array (User Input)

Reads n and then n numbers from the user. Rejects a negative length.

JavaScript
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)}`);

How It Works

Build the array first, then reuse the same sumArray helper. Keeping input and summing separate makes testing easier.

Example 3 — Running Total with Negatives

Print the accumulator after each step so you can see negatives reduce the total.

JavaScript
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}`);

How It Works

Negatives are not special-cased — addition handles them. Tracing the running total is a great whiteboard habit.

🧠 How the Algorithm Adds

1

Set total = 0

Additive identity for an empty start.

Init
2

Visit each value

for (const value of arr)

Loop
3

total += value

Fold the next element into the sum.

Update
=

Return total

After the loop, total is the answer.

🔎 Worked Walkthrough — [1, 2, 3, 4, 5]

Watch the accumulator climb from 0 to 15.

Stepvaluetotal after
start0
111
223
336
4410
5515

Same table works for [10, -2, 7]: 0 → 10 → 8 → 15.

Use Cases

Where array sums show up beyond the interview prompt.

1. Interview Basics

First array traversal drill.

Example: sumArray([1,2,3]).

2. Averages

Sum then divide by n.

Example: average tutorials.

3. Totals in Apps

Cart totals, scores, balances.

Example: add line items.

4. Prefix Sums

Store running totals for ranges.

Example: range queries.

5. Validation

Checksum-style quick totals.

Example: live preview.

6. Next: Maximum

Same pass, keep the best.

Example: related CTA.

Pro Tip: say “accumulator starts at zero” before you write the loop.

Advantages

Why the one-pass accumulator is the right first approach.

  1. 1. Simple to Explain

    One variable, one loop, one update.

  2. 2. Optimal for Unsorted Lists

    You must look at every element anyway.

  3. 3. Tiny Extra Memory

    Only the accumulator — O(1) space.

  4. 4. Handles Edges Naturally

    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.

Usage Tips

Small habits that keep sum solutions interview-ready.

  1. 1. Start at Zero

    Never seed with arr[0] for summing.

  2. 2. One Loop Only

    Do not nest or sort first.

  3. 3. Validate Input

    Guard negative n when reading length.

  4. 4. Trace on Paper

    Write the running total for small arrays.

  5. 5. Know reduce

    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.

Common Pitfalls

Mistakes that commonly break sum-of-array programs.

  1. 1. Starting total at arr[0]

    That pattern is for max/min, not sum.

    → Always start sum at 0.

  2. 2. Skipping Empty Lists

    Crashing when n = 0.

    → Empty sum is 0 with this pattern.

  3. 3. Rejecting Negatives

    Treating them as invalid.

    → Addition already handles them.

  4. 4. Sorting First

    Unnecessary O(n log n) work.

    → One linear pass is enough.

  5. 5. Mixing Strings

    Unvalidated input breaks int conversion.

    → Validate before summing.

Edge Cases

Handle these before claiming the sum is complete.

Empty array

Sum = 0

Result remains 0.

Negatives

Valid input

They reduce the total naturally.

Single element

Sum = that value

[7] → 7.

Invalid input

Validate safely

Handle non-numeric values before summing.

n < 0

Reject length

Raise or re-prompt.

Zeros

No change

Adding 0 leaves total unchanged.

⚖️ Facts Worth Knowing

Handy follow-ups interviewers sometimes ask.

  • Additive identity. Starting at 0 is what makes empty arrays work.
  • Must see every element. You cannot skip values in an unsorted array.
  • Order does not matter. Integer addition is commutative.
  • Product is different. Products start at 1, not 0.

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Sum [1..5]

  • Reproduce Example 1
  • Expect 15

2. Trace [10,-2,7]

  • Show running totals
  • Match Example 3

3. Empty array

  • Confirm sum = 0
  • No special branch needed

4. Average follow-up

  • Sum then / len(arr)
  • Guard empty length

Notes

  • Pattern: accumulator starts at 0, then add each element once.
  • Complexity: O(n) time and O(1) extra space.
  • Production: arr.reduce((a, b) => a + b, 0) is fine after you can write the loop.
  • Next skill: keep a running maximum or minimum with the same one-pass shape.

Quick Takeaway: total = 0; for each value, total += value.

⏱️ Time and Space Complexity

ApproachTimeExtra space
Single passO(n)O(1)
Built-in reduceO(n)O(1)
Sort then addO(n log n)varies

You must read every element, so linear time is optimal for an unsorted array.

Wrap Up

🎉 Conclusion

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.

💡 Best Practices

✅ Do

  • Start total at 0
  • Visit every element once
  • Allow negatives
  • Treat empty as 0
  • Mention reduce after the loop

❌ Don’t

  • Seed total with arr[0]
  • Sort just to sum
  • Crash on empty arrays
  • Skip input validation
  • Confuse with product (starts at 1)

Key Takeaways

Knowledge Unlocked

Five things to remember about summing arrays

Master the accumulator pattern for every later scan.

5
Core concepts
+ 02

Add

total += x

Loop
[] 03

Empty

sum is 0

Edge
- 04

Negatives

just subtract

Input
O 05

Cost

O(n) / O(1)

Analysis

❓ Frequently Asked Questions

Set total = 0, then loop through the array and do total += value for each element.
Zero is the additive identity, so the final total equals the sum of all values.
Yes. The same loop works; negative numbers reduce the total.
Use arr.reduce((a, b) => a + b, 0) in production code. Use loops in interviews to show understanding.
O(n) time and O(1) extra space.
By the accumulator pattern, the answer is 0.
No. Addition is associative and commutative for ordinary numbers.
Say accumulator out loud, start at 0, then walk every element once.
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.

Did you Know? 🔊

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.

Continue to Maximum of an Array

Learn how to find the largest element with a single linear scan.

Maximum of an array tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

9 people found this page helpful