javascripthtml

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?


Solution

  • 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);