Languages
[Edit]
EN

JavaScript - sum array of numbers

0 points
Created by:
Kia-H
546

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

See also

  1. JavaScript - subtract array of numbers

References

  1. Array.prototype.reduce() - JavaScript | MDN

Alternative titles

  1. JavaScript - find sum of array of numbers
  2. JavaScript - sum array of numbers with reduce()
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join