How to sum an array of numbers in JavaScript
Summing arrays of numbers is fundamental for calculating totals, statistical analysis, financial computations, and implementing features like shopping cart totals or data aggregation in JavaScript applications.
With over 25 years of experience in software development and as the creator of CoreUI, I’ve implemented array summation in components like data tables, chart calculations, and financial widgets where accurate total calculations are essential for user interfaces and business logic.
From my extensive expertise, the most elegant and functional approach is using the reduce()
method with an accumulator.
This method is concise, readable, and follows functional programming principles while handling empty arrays gracefully.
Use reduce()
with an accumulator to sum all array elements.
const numbers = [10, 20, 30, 40]
const sum = numbers.reduce((acc, num) => acc + num, 0)
// Result: 100
const prices = [19.99, 25.50, 12.75]
const total = prices.reduce((total, price) => total + price, 0)
// Result: 58.24
The reduce()
method processes each array element, accumulating the sum in the first parameter (acc
or total
). The second parameter is the current array element being processed. The initial value 0
ensures the function works correctly with empty arrays and provides a starting point for the accumulation. Each iteration adds the current number to the running total. The method returns a single value (the sum) rather than a new array, making it perfect for aggregation operations like summing.
Best Practice Note:
This is the same approach we use in CoreUI components for data aggregation, total calculations, and statistical operations across our component library.
Alternative approaches include for
loops or forEach()
, but reduce()
is preferred for functional programming style. Always provide the initial value 0
to handle empty arrays correctly. For very large arrays, consider streaming or chunked processing. The method handles integers, floats, and mixed number types reliably in JavaScript.