Friday, September 8, 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 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. 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 working complete with the opposite representing the worth to be added. You will 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!

  • Responsive and Infinitely Scalable JS Animations

    Again in late 2012 it was not simple to seek out open supply tasks utilizing requestAnimationFrame() – that is the hook that permits Javascript code to synchronize with an online browser’s native paint loop. Animations utilizing this technique can run at 60 fps and ship incredible…

  • Write Better JavaScript with Promises

    You’ve got in all probability heard the discuss across the water cooler about how guarantees are the long run. All the cool children are utilizing them, however you do not see what makes them so particular. Cannot you simply use a callback? What is the large deal? On this article, we’ll…

  • Morphing Elements Using MooTools and CSS

    Morphing a component between CSS lessons is one other nice trick the MooTools JavaScript library allows you to do. Morphing is not essentially the most sensible use of MooTools, but it surely’s nonetheless a trick at your disposal. Step 1: The XHTML The block of content material that can change is…

  • Drag. Drop. Lock.


Supply hyperlink
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments