W3docs

How to Find the Sum of an Array of Numbers

Read this JavaScript tutorial and learn several methods used to find or calculate the sum of an array of numbers. Also, find which is the fastest one.

There are multiple ways to calculate the sum of an array of numbers. Let’s discuss each of them.

reduce()

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

The <kbd class="highlighted">reduce()</kbd> 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

javascript— editable

The 0 in reduce() is the default value. If a 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 concise like this:

Javascript reduce method to find the sum of an array

javascript— editable

for loop

Another method is using a for loop, which is often faster than the <kbd class="highlighted">reduce()</kbd> method:

Javascript for loop to find the sum of an array

javascript— editable

forEach loop

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

Javascript forEach loop calculating the sum of an array

javascript— editable

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?

javascript— editable
Try it Yourself isn't available for this example.

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.