DEV Community

Cover image for The missing sum() method
Tracy Gilmore
Tracy Gilmore

Posted on

The missing sum() method

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?

Oldest comments (5)

Collapse
 
rmmgc profile image
Ramo Mujagic

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

Collapse
 
tracygjg profile image
Tracy Gilmore • Edited

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.

Collapse
 
projektorius96 profile image
Lukas Gaucas • Edited

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) ?

Thread Thread
 
tracygjg profile image
Tracy Gilmore • Edited

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).

Thread Thread
 
projektorius96 profile image
Lukas Gaucas

Thanks for an answer !