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]; […]

The post Sum an Array of Numbers with JavaScript appeared first on David Walsh Blog.


This content originally appeared on David Walsh Blog and was authored by David Walsh

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!

The post Sum an Array of Numbers with JavaScript appeared first on David Walsh Blog.


This content originally appeared on David Walsh Blog and was authored by David Walsh


Print Share Comment Cite Upload Translate Updates
APA

David Walsh | Sciencx (2023-09-07T02:06:45+00:00) Sum an Array of Numbers with JavaScript. Retrieved from https://www.scien.cx/2023/09/07/sum-an-array-of-numbers-with-javascript/

MLA
" » Sum an Array of Numbers with JavaScript." David Walsh | Sciencx - Thursday September 7, 2023, https://www.scien.cx/2023/09/07/sum-an-array-of-numbers-with-javascript/
HARVARD
David Walsh | Sciencx Thursday September 7, 2023 » Sum an Array of Numbers with JavaScript., viewed ,<https://www.scien.cx/2023/09/07/sum-an-array-of-numbers-with-javascript/>
VANCOUVER
David Walsh | Sciencx - » Sum an Array of Numbers with JavaScript. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2023/09/07/sum-an-array-of-numbers-with-javascript/
CHICAGO
" » Sum an Array of Numbers with JavaScript." David Walsh | Sciencx - Accessed . https://www.scien.cx/2023/09/07/sum-an-array-of-numbers-with-javascript/
IEEE
" » Sum an Array of Numbers with JavaScript." David Walsh | Sciencx [Online]. Available: https://www.scien.cx/2023/09/07/sum-an-array-of-numbers-with-javascript/. [Accessed: ]
rf:citation
» Sum an Array of Numbers with JavaScript | David Walsh | Sciencx | https://www.scien.cx/2023/09/07/sum-an-array-of-numbers-with-javascript/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.