Saturday, July 27, 2024
HomeTechnologySoftwareSum an Array of Numbers with JavaScript

Sum an Array of Numbers with JavaScript

Date:

Related stories

Hull KR 40-16 London Broncos

Highlights from the Betfred Super League clash between...

Google Pixel 9 leaks in all colors

It's been a crazy week for Pixel leaks,...

Have a Delicious Weekend. | Cup of Jo

What are you up to this weekend? We...

Assassin’s Creed Surprises Fans At 2024 Summer Olympic Games

I didn’t know the 2024 Olympic Games were...
spot_imgspot_img

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!

  • fetch API

    One of the worst kept secrets about AJAX on the web is that the underlying API for it, XMLHttpRequest, wasn’t really made for what we’ve been using it for.  We’ve done well to create elegant APIs around XHR but we know we can do better.  Our effort to…

  • From Webcam to Animated GIF: the Secret Behind chat.meatspac.es!


Source link

Latest stories

spot_img