Software

Sum an Array of Numbers with JavaScript

[ad_1]

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!

  • Introducing MooTools Templated

    One major problem with creating UI components with the MooTools JavaScript framework is that there isn’t a great way of allowing customization of template and ease of node creation. As of today, there are two ways of creating: new Element Madness The first way to create UI-driven…

  • 5 Awesome New Mozilla Technologies You’ve Never Heard Of

    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…

  • CSS 3D Folding Animation
  • Multiple Backgrounds with CSS

    Anyone that’s been in the web development industry for 5+ years knows that there are certain features that we should have had several years ago. One of those features is the HTML5 placeholder; we used JavaScript shims for a decade before placeholder came…


[ad_2]
Source link
Show More

admin

Makes Noise is a blog where you can find all the juicy details on a variety of topics including health and fitness, technology, lifestyle, entertainment, love and relationships, beauty and makeup, sports and so much more. The blog is updated regularly to make sure you have all the latest and greatest information on the topics that matter most to you.

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button