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!
Back in late 2012 it was not easy to find open source projects using requestAnimationFrame()
- this is the hook that allows Javascript code to synchronize with a web browser's native paint loop. Animations using this method can run at 60 fps and deliver fantastic...
I get asked loads of questions every day but I'm always surprised that they're rarely questions about code or even tech -- many of the questions I get are more about non-dev stuff like what my office is like, what software I use, and oftentimes...
Note: All credit for Fx.Explode goes to Jan Kassens.
One of the awesome pieces of code in MooTools Core Developer Jan Kassens' sandbox is his Fx.Explode functionality. When you click on any of the designated Fx.Explode elements, the elements "explode" off of the...
Google Analytics is an outstanding website analytics tool that gives you way more information about your website than you probably need. Better to get more than you want than not enough, right? Anyways I check my website statistics more often than I should and...
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.