Sum an Array of Numbers with JavaScript


It is uncommon that I am disenchanted by the JavaScript language not having a perform that I want. One such case was summing an array of numbers — I used to be anticipating Math.sum or a likewise, baked in API. Concern not — summing an array of numbers is straightforward utilizing Array.prototype.cut back!

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

The 0 represents the beginning worth whereas with a and b, one represents the working whole with the opposite representing the worth to be added. You will additionally notice that utilizing cut back prevents negative effects! I would nonetheless desire one thing like Math.sum(...numbers) however a easy cut back will do!

  • Write Simple, Elegant and Maintainable Media Queries with Sass
  • JavaScript Promise API

    Whereas synchronous code is simpler to comply with and debug, async is usually higher for efficiency and suppleness. Why “maintain up the present” when you may set off quite a few requests without delay after which deal with them when every is prepared?  Guarantees are turning into a giant a part of the JavaScript world…

  • Scrolling “Go To Top” Link Using Dojo

    One of the well-liked code snippets of posted on my weblog has been the scrolling “Go To Prime” hyperlink snippet. The premise of the snippet is easy: as soon as the person scrolls a component (normally the BODY ingredient) previous a given threshold, a “Go…

  • Web Notifications API

    Each UI framework has the identical set of widgets which have grow to be virtually important to fashionable websites: modals, tooltips, button varieties, and notifications.  One downside I discover is every website having their very own widget colours, kinds, and extra — customers do not get a constant expertise.  Apparently the…


Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles