Tuesday, September 12, 2023
HomeSoftware DevelopmentSum an Array of Numbers with JavaScript

Sum an Array of Numbers with JavaScript

It is uncommon that I am disenchanted by the JavaScript language not having a operate 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. 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 operating complete with the opposite representing the worth to be added. You may additionally observe that utilizing cut back prevents unintended effects! I would nonetheless want one thing like Math.sum(...numbers) however a easy cut back will do!

  • Welcome to My New Office

    My first skilled internet growth was at a small print store the place I sat in a windowless cubical all day. I suffered that boxed in atmosphere for nearly 5 years earlier than I used to be capable of finding a distant job the place I labored from house. The primary…

  • Serving Fonts from CDN

    For max efficiency, everyone knows we should put our belongings on CDN (one other area).  Together with these belongings are customized internet fonts.  Sadly customized internet fonts by way of CDN (or any cross-domain font request) do not work in Firefox or Web Explorer (appropriately so, by spec) although…



Please enter your comment!
Please enter your name here

Most Popular

Recent Comments