4

I want to calculate sum with forEach array function in JavaScript. But I don't get what I want.

function sum(...args) {
  args.forEach(arg => {
    var total = 0;
    total += arg;
    console.log(total);
 });
}
sum(1, 3);

How to get total with forEach, or use reduce method?

Al Fahad
  • 2,378
  • 5
  • 28
  • 37
Milos N.
  • 4,416
  • 6
  • 18
  • 31

4 Answers4

16

You may better use Array#reduce, because it is made for that kind of purpose.

It takes a start value, of if not given, it take the first two elements of the array and reduces the array literally to a single value. If the array is empty and no start value is supplied, it throws an error.

function sum(...args) {
    return args.reduce((total, arg) => total + arg, 0);
}

console.log(sum(1, 3));
console.log(sum(1));
console.log(sum());
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
8

You should put total outside forEach loop:

function sum(...args) {
  var total = 0;
  args.forEach(arg => {
    total += arg;
  });
  console.log(total);
}

sum(1, 3);
Al Fahad
  • 2,378
  • 5
  • 28
  • 37
BladeMight
  • 2,670
  • 2
  • 21
  • 35
1

You have to move the total=0; out of the loop - it is being reset to 0 on each iteration

function sum(...args) {
var total = 0;
args.forEach(arg => {
  total += arg;
  console.log(total); 
 });
}
sum(1, 3); // gives 1, 4 or in other words 0+1=1 then 1+3=4
function sum(...args) {
var total = 0;
args.forEach(arg => {
  total += arg;
  console.log(total);
 });
}
sum(1, 3);
gavgrif
  • 15,194
  • 2
  • 25
  • 27
0
function sum(...args) {
    return args.reduce((total, amount) => total + amount); 
}

console.log(sum(1,3));
Koen
  • 370
  • 2
  • 7