Sum an Array of Numbers with JavaScript


It is uncommon that I am dissatisfied 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. Worry not — summing an array of numbers is simple utilizing 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 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 scale back prevents uncomfortable side effects! I would nonetheless want one thing like Math.sum(...numbers) however a easy scale back will do!

  • Introducing MooTools Templated

    One main drawback with creating UI elements with the MooTools JavaScript framework is that there is not a good way of permitting customization of template and ease of node creation. As of right now, there are two methods of making: new Factor Insanity The primary method to create UI-driven…

  • 5 Ways that CSS and JavaScript Interact That You May Not Know About

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *