The missing sum() method
Tracy Gilmore

Tracy Gilmore @tracygjg

About: After my first contact with a computer in the 1980's, I taught myself to program in BASIC and Z80 assembler. I went on to study Computer Science and have enjoyed a long career in Software Engineering.

Location:
Somerset, UK
Joined:
Jul 16, 2017

The missing sum() method

Publish Date: Dec 11 '22
5 5

The current specification for the JavaScript Math object (namespace), according to MDN, comprises of 8 properties and 35 methods.

The extensive range of methods include a variety of Logarithmic Trigonometric and utility functions. Yet there is, at least in my eyes, a glaringly obvious omission.

There is min and max that can both take numerous arguments and return a single value, but where is the sum function?

Instead we have to resort to coding this function ourselves, which is far from efficient.

Examples include:

function sum(...nums) {
  return nums.reduce((tot, num) => tot + num);
}

// or

const sum = (...nums) => nums.reduce((tot, num) => tot + num);
Enter fullscreen mode Exit fullscreen mode

We could polyfill but extending standard objects like Math is seldom a good decision.

I really would like to know why this method is missing, any suggestions?

Comments 5 total

  • Ramo Mujagic
    Ramo MujagicDec 12, 2022

    Maybe because one can create one-liner for it, as you have demonstrated 🤔

    • Tracy Gilmore
      Tracy GilmoreDec 13, 2022

      You could also create a one-liner (now we have arrow functions, rest operators and reduce methods) for min, max, etc. but having it implemented inside the JS engine will always be faster.

      • LG
        LGDec 15, 2022

        Does your sentence mean that implementing arbitrary functions in code source is never fast as implemented in programming language, in this case EcmaScript (JavaScript engine) ?

        • Tracy Gilmore
          Tracy GilmoreDec 15, 2022

          Having the function built into the language will most often run faster than using the language to implement the function. If this were not the case the role of WebAssembly would be rather questionable.

          The closer "to the metal" the function implementation the more performant it is likely to be. JavaScript is about as far from the metal as you can get (on the same box) so is less likely to be more performant than the same function implemented in other languages.

          Also consider, the functions I gave above can be called with Numbers, BigInts, Strings and even Arrays (not necessarily with desirable results).

          • LG
            LGDec 16, 2022

            Thanks for an answer !

Add comment