How to Get the Sum of an Array of Numbers in JavaScript
Calculating the sum of all numbers in an array is a fundamental operation in programming, essential for everything from calculating a shopping cart total to aggregating data for a report. While you could use a simple loop, modern JavaScript provides a more concise and declarative way to achieve this using the Array.prototype.reduce() method.
This guide will teach you how to use the powerful reduce() method to sum an array of numbers. We will also cover the traditional for...of loop as a readable alternative.
The Modern Method (Recommended): Array.prototype.reduce()
The reduce() method is the perfect tool for this job. It iterates through an array and "reduces" it to a single value by applying a function that combines each element with an accumulating result.
The reduce() method takes two arguments:
- A callback function that receives an
accumulatorand thecurrentValue. On each step, it should return the new value for the accumulator. - An initial value for the accumulator. For a sum, this should be
0.
We have an array of numbers and need to calculate their total sum.
// Problem: How to get the sum of all numbers in this array?
const numbers = [5, 15, 45];
Solution:
const numbers = [5, 15, 45];
const sum = numbers.reduce((accumulator, currentValue) => {
return accumulator + currentValue;
}, 0); // The `0` is the initial value for the accumulator
console.log(sum);
Output:
65
This can be written even more concisely with an implicit return:
const sum = numbers.reduce((acc, val) => acc + val, 0);
This functional approach is the standard, modern best practice for its conciseness and readability.
The Traditional Method: The for...of Loop
Before functional methods like reduce() were common, this problem was solved with a standard for loop. This imperative approach is still perfectly valid, highly performant, and can be easier to understand for those new to functional programming.
The logic:
- Initialize a
sumvariable to0. - Loop through each
numberin the array. - On each iteration, add the current
numberto thesum.
Solution
const numbers = [5, 15, 45];
let sum = 0;
for (const number of numbers) {
sum += number;
}
console.log(sum);
Output:
65
This method is slightly more verbose but is very clear and easy to debug.
Handling Arrays with Non-Numeric Values
Real-world data is often messy. If your array might contain non-numeric values, simply adding them will result in NaN (Not-a-Number) or incorrect string concatenation.
example of code with problems:
const mixedArray = [10, 'hello', 20, null, 30];
// This will produce an incorrect result.
const result = mixedArray.reduce((acc, val) => acc + val, 0);
console.log(result);
Output:
10hello20null30
Solution: you must first filter the array to ensure you are only working with numbers.
const mixedArray = [10, 'hello', 20, null, 30];
const sum = mixedArray
.filter(item => typeof item === 'number') // Keep only the numbers
.reduce((acc, val) => acc + val, 0); // Then, sum them
console.log(sum);
Output:
60
This two-step chain of filter() and reduce() is a robust and readable pattern for handling imperfect data.
Conclusion
Summing the elements of an array is a simple task with clear, modern solutions in JavaScript.
- The
array.reduce((acc, val) => acc + val, 0)method is the most concise and recommended approach. It is a powerful functional pattern that is a cornerstone of modern JavaScript. - A traditional
for...ofloop is a perfectly valid and readable alternative that achieves the same result. - For arrays with mixed data types, always
filter()the array first to ensure you are only summing valid numbers.