Sum an Array of Numbers with JavaScript
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!
My trip to Mozilla Summit 2013 was incredible. I've spent so much time focusing on my project that I had lost sight of all of the great work Mozillians were putting out. MozSummit provided the perfect reminder of how brilliant my colleagues are and how much...
MooTools has always gotten a bit of grief for not inherently using and standardizing namespaced-based JavaScript classes like the Dojo Toolkit does. Many developers create their classes as globals which is generally frowned up. I mostly disagree with that stance, but each to their own. In any event...
Let's be honest, form validation with JavaScript can be a real bitch. On a real basic level, however, it's not that bad. HTML5 has jumped in to some extent, providing a few attributes to allow us to mark fields as required or only valid if matching...
A while back I shared a clever technique for creating triangles with only CSS. Over the past year, I've found CSS triangles incredibly effective, especially when looking to create tooltips or design elements with a likewise pointer pattern. There's another common shape...
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 besum(nums)
orsum(...nums)
?sum([1,2,3])
orsum(1,2,3)
? I kinda prefer the latter.