Find Sum of Array in JavaScript

Beginner
⏱️ 8 min read
📚 Updated: May 2026
🎯 2 Code Examples
Arrays

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).

Tip: you can include negatives (like -2). Empty input is treated as “no numbers”.

Live result
Press “Compute sum”.

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

Pseudocode
function arraySum(a, n):
    sum ← 0
    for i from 0 to n-1:
        sum ← sum + a[i]
    return sum
1

Sum of a fixed array

This matches the classic example: {1,2,3,4,5} sums to 15.

JavaScript
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);
Try it Yourself
2

Sum of an array (user input)

Reads n, then reads n integers. Uses long long for the running total.

JavaScript
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));
Try it Yourself

❓ FAQ

Initialize sum to 0, then loop through the array and add each element: sum += arr[i]. Print sum at the end.
Because 0 is the identity for addition. If you start from 0 and add every element once, you get exactly the total.
Nothing special is needed. The same loop works; negative values simply subtract from the total.
Use long long if the array may contain big values or many items. It reduces overflow risk compared to int.
O(n) because you must look at each of the n elements at least once.

🔄 Input / output examples

ArraySum
{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.

n = 0

Empty array

The sum of zero numbers is 0. The loop runs zero times and sum stays 0.

Overflow

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.

Input

Invalid reads

Always validate parsed values from strings so invalid tokens do not silently corrupt the sum.

⏱️ Time and space complexity

ApproachTimeExtra space
One loop through n elementsO(n)O(1)

Summary

  • Pattern: sum = 0, then sum += arr[i] for each element.
  • Use: choose long long for safer totals.
  • Complexity: O(n) time, O(1) extra space.
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.

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