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!
CSS animations are a lot of fun; the beauty of them is that through many simple properties, you can create anything from an elegant fade in to a WTF-Pixar-would-be-proud effect. One CSS effect somewhere in between is the CSS flip effect, whereby there's...
Your early CSS books were instrumental in pushing my love for front end technologies. What was it about CSS that you fell in love with and drove you to write about it?
At first blush, it was the simplicity of it as compared to the table-and-spacer...
Every once in a while I find a tiny JavaScript library that does something very specific, very well. My latest find, Fokus, is a utility that listens for text selection within the page, and when such an event occurs, shows a beautiful modal dialog in...
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.