Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sum function in Javascript

When I create a simple Visual Studio project and add JavaScript and HTML items to it, I seem to have access to all built in functions, such as indexOf(), search(), slice(), range(), etc...

However, when I try to use the sum() function (e.g. console.log(sum(range(1, 10)));) I get the following error message:

Uncaught ReferenceError: sum is not defined

Putting this message within double quotes and adding the JavaScript keyword in Google did not bring up a webpage that tells me what I am missing, hence this basic question here.

Am I missing something like a library that sum is included in? What am I doing wrong that only this particular function is not recognized?


2 Answers

There is no built-in sum() function in Javascript.

You can create one easily with reduce():

function sum(arr) {
   return arr.reduce(function (a, b) {
      return a + b;
   }, 0);
}

var numbers = [1, 2, 3];

console.log(sum(numbers));

Or use reduce() as a oneliner:

var numbers = [1, 2, 3];

var totalSum = numbers.reduce(function (a, b) { return a + b; }, 0);

console.log(totalSum);
like image 52
Jaqen H'ghar Avatar answered Oct 21 '25 02:10

Jaqen H'ghar


Just for the sake of it, here's a nice ES6 version:

const sum = (arr=[]) => arr.reduce((total, val) => total + val);
like image 44
Michael Rosefield Avatar answered Oct 21 '25 01:10

Michael Rosefield



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!