Sum an Array of Numbers with JavaScript


It is uncommon that I am upset by the JavaScript language not having a perform that I would like. One such case was summing an array of numbers — I used to be anticipating Math.sum or a likewise, baked in API. Worry not — summing an array of numbers is simple 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 be aware that utilizing cut back prevents negative effects! I would nonetheless favor one thing like Math.sum(...numbers) however a easy cut back will do!

  • 5 Awesome New Mozilla Technologies You’ve Never Heard Of

    My journey to Mozilla Summit 2013 was unimaginable.  I’ve spent a lot time specializing in my venture that I had overpassed the entire nice work Mozillians have been placing out.  MozSummit supplied the proper reminder of how sensible my colleagues are and the way a lot…

  • Regular Expressions for the Rest of Us

    In the end you will run throughout a daily expression. With their cryptic syntax, complicated documentation and large studying curve, most builders accept copying and pasting them from StackOverflow and hoping they work. However what if you happen to may decode common expressions and harness their energy? In…

  • Duplicate the jQuery Homepage Tooltips Using MooTools

    The jQuery homepage has a reasonably suave tooltip-like impact as seen under: This is the best way to accomplish this identical impact utilizing MooTools. The XHTML The above XHTML was taken straight from the jQuery homepage — no modifications. The CSS The above CSS has been barely modified to match the CSS guidelines already…

  • CSS @supports

    Characteristic detection by way of JavaScript is a consumer facet finest follow and for all the suitable causes, however sadly that very same performance hasn’t been out there inside CSS.  What we find yourself doing is repeating the identical properties a number of occasions with every browser prefix.  Yuck.  One other factor we…


Recent Articles

Related Stories

Leave A Reply

Please enter your comment!
Please enter your name here

Stay on op - Ge the daily news in your inbox