Code Logo

Sum with Array.reduce()

Published at25 Jul 2026
JavaScript Functions Easy 0 views
Like0

Write a JavaScript function that uses the Array.reduce() method to calculate the sum of all elements in an array. The reduce method is a powerful array method that executes a reducer function on each element, resulting in a single output value.

The reduce method takes two parameters: a callback function and an initial value. The callback receives the accumulator (running total) and the current element. For each element, add it to the accumulator and return the new accumulator value. Start with an initial value of 0 to handle empty arrays correctly.

Using reduce for summation is idiomatic JavaScript and avoids explicit loop variables. The callback function can be written as an arrow function for concise syntax: (acc, curr) => acc + curr. The reduce method is available on all JavaScript arrays and is widely used for aggregation operations.

Time complexity is O(n) where n is the array length. The reduce method iterates through each element exactly once. Space complexity is O(1) since only the accumulator is maintained.

Edge cases include empty arrays (return 0 with initial value), single-element arrays (return that element), and arrays with negative numbers. The reduce method handles all these cases naturally when provided with an initial accumulator value.

Example Input & Output

Example 1
Input
[-1,-2,-3]
Output
-6
Explanation

All negative numbers

Example 2
Input
[5]
Output
5
Explanation

Single element

Example 3
Input
[]
Output
0
Explanation

Empty array returns 0

Example 4
Input
[10,-2,3]
Output
11
Explanation

10 + (-2) + 3 = 11

Example 5
Input
[1,2,3,4,5]
Output
15
Explanation

Sum is 1+2+3+4+5 = 15

Algorithm Flow

Recommendation Algorithm Flow for Sum with Array.reduce()
Recommendation Algorithm Flow for Sum with Array.reduce()

Solution Approach

Sum all elements of an array using reduce(). The reduce method executes a reducer function on each element, accumulating a single result. Start with an initial accumulator value of 0 and add each element.

function solution(arr) { return arr.reduce(function(acc, n) { return acc + n; }, 0); }

reduce() is versatile: it can sum, multiply, flatten, group, and more. The initial value parameter is important for empty arrays, providing a default return value.

Time O(n), Space O(1).

Best Answers

javascript - Approach 1
function solution(nums) {
  return nums.reduce(function(acc, curr) {
    return acc + curr;
  }, 0);
}