Sum with Array.reduce()
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
All negative numbers
Single element
Empty array returns 0
10 + (-2) + 3 = 11
Sum is 1+2+3+4+5 = 15
Algorithm Flow

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.
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
function solution(nums) {
return nums.reduce(function(acc, curr) {
return acc + curr;
}, 0);
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
