Home Software Development Sum an Array of Numbers with JavaScript

Sum an Array of Numbers with JavaScript

0
Sum an Array of Numbers with JavaScript
[ad_1]

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


[ad_2]