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
    5 Ways that CSS and JavaScript Interact That You May Not Know About

    CSS and JavaScript:  the lines seemingly get blurred by each browser release.  They have always done a very different job but in the end they are both front-end technologies so they need do need to work closely.  We have our .js files and our .css, but...

  • By
    Facebook Open Graph META Tags

    It's no secret that Facebook has become a major traffic driver for all types of websites.  Nowadays even large corporations steer consumers toward their Facebook pages instead of the corporate websites directly.  And of course there are Facebook "Like" and "Recommend" widgets on every website.  One...

Incredible Demos

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!