Find the sum of an array with Javascript
Published
As often with programming, there are multiple ways to do something. Let’s check out a few ways to sum the numbers in an array.
Table of contents
- Using a for loop to sum an array
- Using forEach to sum an array in Javascript
- Using reduce to sum an array in Javascript
- Making a function to sum an array in Javascript
Using a for loop to sum an array
You can use a basic for loop to accumulate the sum of values in an accumulator variable.
const myArray = [2, 3, 5];
// We'll define an accumulator variable
let total = 0;
// We then loop over the array and add them to the accumulator
for (let index = 0; index < length; index++) {
total += myArray[index];
}
console.log(total); // prints 10
Using forEach to sum an array in Javascript
Using a forEach works pretty much the same way as the for loop but removes some of the boilerplate code.
const myArray = [2, 3, 5];
// We'll define an accumulator variable
let total = 0;
arr.forEach((number) => (total += number));
console.log(total); // prints 10
Using reduce to sum an array in Javascript
reduce is an Array method just like map but is often shunned by beginners who do not understand it. By passing in an addition function, we get a pretty sweet one-liner that will sum every item in the array.
const myArray = [2, 3, 5];
const total = myArray.reduce((previous, current) => previous + current, 0);
console.log(total); // prints 10
Making a function to sum an array in Javascript
Let’s reuse our reduce code to create a function:
function sumArray(arr) {
return arr.reduce((p, c) => p + c, 0);
}
While you could define this function as a method on the Array prototype, it is not recommended to do so as it could clash with other libraries. You’ll also notice that we’re not checking for types here. I recommend using Typescript to avoid any sort of typing issues, especially with strings.
The same function in Typescript would look like this and will let your IDE inform you if the input is invalid.
function sumArray(arr: number[]) {
return arr.reduce((p, c) => p + c, 0);
}