How to Find the Sum of an Array of Numbers

There are multiple ways that you should use in order to calculate the sum of an array of numbers. Let’s discuss each of them and try examples.

reduce()

You can use the reduce() method to find the sum of an array of numbers.

The reduce() method executes the specified reducer function on each member of the array resulting in a single output value as in the following example:

Javascript reduce method to find the sum of an array
let arr = [10, 20, 30, 40]; let sum = arr.reduce(function (a, b) { return a + b; }, 0); console.log(sum); // Output: 100

The 0 in is the default value. If default value is not supplied, the first element in the array will be used. If the array is empty, you will get an error.

If you use ES2015, you can make it more verbose like this:

Javascript reduce method to find the sum of an array
const sum = [10, 20, 30].reduce((a, b) => a + b) console.log(sum); // Output: 60

for loop

Another fast method is using for loop which is even faster as the reduce() method:

Javascript for loop to find the sum of an array
let numbers = [10, 20, 30, 40, 50] let sum = 0; for (let i = 0; i < numbers.length; i++) { sum += numbers[i] } console.log(sum) // Output: 150

forEach loop

An alternative way of calculating the array of numbers is using forEach loop like this:

Javascript forEach loop calculating the array of numbers
const arr = [10, 20, 30, 40]; let result = 0; arr.forEach(number => { result += number; }) console.log(result); // Output: 100

How to add only certain elements of an array?

To find the sum of certain elements of an array in JavaScript, you can use a loop to iterate over the elements and add them up. Here's an example code that adds up the elements from indices 3-7 of an array:

How to add only certain elements of an array in JavaScript?
const numbers = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]; let sum = 0; for (let i = 3; i <= 7; i++) { sum += numbers[i]; } console.log(sum); // Output: 60 (which is the sum of 8 + 10 + 12 + 14 + 16)

In this example, we define an array of 10 numbers and then use a for loop to iterate over the elements with indices 3-7 (which is the fourth through eighth elements of the array). The loop adds up each element to a running total stored in the sum variable.

After the loop completes, we have the sum of the elements with indices 3-7 stored in the sum variable, which we log to the console.

You can adjust the starting and ending indices in the loop to add up different ranges of elements in the array.

The reduce() method

The reduce() method invokes a reducer function provided on each element of the array and results in single output value. It executes the callback once for each assigned value present in the array taking four arguments: accumulator, currentValue, currentIndex, array. It is recommended to provide default value such as 0 for performing addition and 1 for performing multiplication.