To get the sum of an array in JavaScript, we can use the JavaScript Array reduce() method. Here is the setup for how this can be done:
var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];
function sumArray(total, item) {
return total + item;
}
console.log(numbers.reduce(sumArray));
#Output
45
We can shorten our code even more by using the JavaScript arrow function.
var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];
var sumOfNumbers = numbers.reduce((a, b) => a + b);
console.log(sumOfNumbers);
#Output
45
We can also use a for loop to sum the numbers of an array easily.
var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];
var total = 0;
for( var i =0; i<numbers.length; i++ ){
total += numbers[i];
}
console.log(total);
#Output
45
When working with collections of data in JavaScript, the ability to summarize the data easily is valuable.
One such case is if you want to get the sum of an array of numbers.
To calculate the sum of an array of numbers in JavaScript, the easiest way is with the reduce() method.
Below again we show you how to get the sum of an array of numbers in JavaScript.
var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];
function sumArray(total, item) {
return total + item;
}
console.log(numbers.reduce(sumArray));
#Output
45
Using a For Loop to Get the Sum of an Array in JavaScript
Another way you can add numbers of an array together is with a for loop.
To add the numbers of an array up, initialize a variable that will keep the running sum and then add each element to the running sum.
Below shows you how to get the sum of an array of numbers in JavaScript with a for loop.
var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];
var total = 0;
for( var i =0; i<numbers.length; i++ ){
total += numbers[i];
}
console.log(total);
#Output
45
We can put our code in a function to reuse the function to sum an array.
var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];
function sumArray(arr){
var total = 0;
for( var i =0; i<arr.length; i++ ){
total += arr[i];
}
return total;
};
console.log(sumArray(numbers));
#Output
45
Hopefully this article has been useful for you to learn how to get the sum of an array in JavaScript.