Skip to content

Sum an Array of Numbers with JavaScript


It is uncommon that I am disillusioned by way of the JavaScript language no longer having a serve as that I want. One such case was once summing an array of numbers — I used to be anticipating Math.sum or a likewise, baked in API. Worry no longer — summing an array of numbers is straightforward the use of Array.prototype.scale back!

const numbers = [1, 2, 3, 4];
const sum = numbers.scale back((a, b) => a + b, 0);

The 0 represents the beginning price whilst with a and b, one represents the working general with the opposite representing the worth to be added. You can additionally observe that the use of scale back prevents uncomfortable side effects! I might nonetheless want one thing like Math.sum(...numbers) however a easy scale back will do!

  • Create Namespaced Classes with MooTools

    MooTools has all the time gotten a bit of of grief for no longer inherently the use of and standardizing namespaced-based JavaScript categories just like the Dojo Toolkit does.  Many builders create their categories as globals which is normally frowned up.  I most commonly disagree with that stance, however every to their very own.  In any match…

  • How to Create a Twitter Card