Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate sum with forEach function? [duplicate]

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?

like image 396
Milosh N. Avatar asked Nov 14 '25 13:11

Milosh N.


2 Answers

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());
like image 161
Nina Scholz Avatar answered Nov 17 '25 03:11

Nina Scholz


You should put total outside forEach loop:

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

sum(1, 3);
like image 29
BladeMight Avatar answered Nov 17 '25 04:11

BladeMight



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!