Sum an Array of Numbers with JavaScript

By  on  

It's rare that I'm disappointed by the JavaScript language not having a function that I need. One such case was summing an array of numbers -- I was expecting Math.sum or a likewise, baked in API. Fear not -- summing an array of numbers is easy using Array.prototype.reduce!

const numbers = [1, 2, 3, 4];
const sum = numbers.reduce((a, b) => a + b, 0);

The 0 represents the starting value while with a and b, one represents the running total with the other representing the value to be added. You'll also note that using reduce prevents side effects! I'd still prefer something like Math.sum(...numbers) but a simple reduce will do!

Recent Features

  • By
    6 Things You Didn’t Know About Firefox OS

    Firefox OS is all over the tech news and for good reason:  Mozilla's finally given web developers the platform that they need to create apps the way they've been creating them for years -- with CSS, HTML, and JavaScript.  Firefox OS has been rapidly improving...

  • By
    JavaScript Promise API

    While synchronous code is easier to follow and debug, async is generally better for performance and flexibility. Why "hold up the show" when you can trigger numerous requests at once and then handle them when each is ready?  Promises are becoming a big part of the JavaScript world...

Incredible Demos

  • By
    CSS Background Animations

    Background animations are an awesome touch when used correctly.  In the past, I used MooTools to animate a background position.  Luckily these days CSS animations are widely supported enough to rely on them to take over JavaScript-based animation tasks.  The following simple CSS snippet animates...

  • By
    CSS Vertical Center with Flexbox

    I'm 31 years old and feel like I've been in the web development game for centuries.  We knew forever that layouts in CSS were a nightmare and we all considered flexbox our savior.  Whether it turns out that way remains to be seen but flexbox does easily...

Discussion

  1. Chris Zuber

    Initializing with 0 might not be necessary since it takes the value from the first item in the array if not provided (and then skips the first item for the rest). It’s very slightly slower to set it to 0.

    Here’s what I wonder though… Suppose this were in some math.js module. Would it be sum(nums) or sum(...nums)? sum([1,2,3]) or sum(1,2,3)? I kinda prefer the latter.

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!