JavaScript Program to Find Sum of Array Elements
You can find the sum of array elements in JavaScript by using
array.reduce((acc, val) => acc + val, 0) which adds all numbers together.Examples
Input[1, 2, 3, 4, 5]
Output15
Input[10, -2, 7, 0]
Output15
Input[]
Output0
How to Think About It
To find the sum of numbers in an array, think of adding each number one by one starting from zero. You keep a running total and add each element to it until you reach the end of the array.
Algorithm
1
Start with a total sum set to zero.2
Go through each element in the array one by one.3
Add the current element's value to the total sum.4
After processing all elements, return the total sum.Code
javascript
const numbers = [1, 2, 3, 4, 5]; const sum = numbers.reduce((acc, val) => acc + val, 0); console.log(sum);
Output
15
Dry Run
Let's trace the array [1, 2, 3, 4, 5] through the code to see how the sum is calculated.
1
Initialize sum
sum starts at 0
2
Add first element
sum = 0 + 1 = 1
3
Add second element
sum = 1 + 2 = 3
4
Add third element
sum = 3 + 3 = 6
5
Add fourth element
sum = 6 + 4 = 10
6
Add fifth element
sum = 10 + 5 = 15
| Current sum after adding element |
|---|
| 1 |
| 3 |
| 6 |
| 10 |
| 15 |
Why This Works
Step 1: Starting with zero
We begin with a total sum of 0 because adding zero does not change the sum.
Step 2: Adding each element
Each element in the array is added to the running total using the + operator.
Step 3: Using reduce method
The reduce method applies a function that accumulates the sum by processing each element in order.
Alternative Approaches
Using a for loop
javascript
const numbers = [1, 2, 3, 4, 5]; let sum = 0; for (let i = 0; i < numbers.length; i++) { sum += numbers[i]; } console.log(sum);
This method is straightforward and easy to understand but requires more lines of code.
Using for...of loop
javascript
const numbers = [1, 2, 3, 4, 5]; let sum = 0; for (const num of numbers) { sum += num; } console.log(sum);
This is a cleaner loop syntax that is easy to read and write.
Complexity: O(n) time, O(1) space
Time Complexity
The program visits each element once to add it, so the time grows linearly with the number of elements.
Space Complexity
Only a single variable is used to keep the sum, so extra memory use is constant.
Which Approach is Fastest?
All methods have similar time and space complexity; reduce is concise, while loops may be more explicit.
| Approach | Time | Space | Best For |
|---|---|---|---|
| reduce method | O(n) | O(1) | Concise functional code |
| for loop | O(n) | O(1) | Explicit control and clarity |
| for...of loop | O(n) | O(1) | Readable and modern syntax |
Use
reduce for concise and functional-style summing of array elements.Forgetting to provide the initial value (0) to
reduce can cause errors with empty arrays.