EN
JavaScript - sum array of numbers
0
points
In this article, we would like to show you how to find the sum of an array of numbers using JavaScript.
Quick solution:
// ONLINE-RUNNER:browser;
const numbers = [1, 2, 3];
const sum = (accumulator, number) => accumulator + number;
console.log(numbers.reduce(sum)); // 6
Alternative solution
In this section, we present an alternative solution for older JavaScript versions.
// ONLINE-RUNNER:browser;
function add(accumulator, number) {
return accumulator + number;
}
var numbers = [1, 2, 3];
var sum = numbers.reduce(add, 0); // reduce(callbackFunction, initialValue);
console.log(sum); // 6