Get the Sum of an Array of Numbers in JavaScript

avatar

Borislav Hadzhiev

Thu Oct 14 20212 min read

Get the Sum of an Array of Numbers #

To get the sum of an array of numbers:

  1. Use the reduce() method to iterate over the array, passing it a function as the first parameter and an initial value of 0 as the second.
  2. On each iteration increment the accumulated sum with the current value of the array.
index.js
const arr = [5, 15, 45]; const sum = arr.reduce((accumulator, value) => { return accumulator + value; }, 0); console.log(sum); // ๐Ÿ‘‰๏ธ 65

The accumulator parameter is initially set to 0, because that's what we passed as the second parameter to the reduce method.

With each iteration, we increment the accumulator with the current value of the array until we calculate the total.

An alternative and perhaps simpler approach is to use a for...of loop.

To get the sum of an array of numbers:

  1. Declare a sum variable using the let keyword and set it to 0.
  2. Use the for...of loop to iterate over the array and on each iteration increment the sum variable with the current value.
index.js
const arr = [5, 15, 45]; let sum = 0; for (const value of arr) { sum += value; } console.log(sum); // ๐Ÿ‘‰๏ธ 65

The for...of loop allows us to iterate over an array.

Notice that we declare the sum variable using the let keyword. Had we declared the variable using const, we wouldn't be able to reassign it.

On each iteration we increment the value stored in the sum variable until we get the total.

The for...of loop is not supported by Internet Explorer. If you have to support the browser, use a basic for loop instead.
index.js
// Supported by IE const arr = [5, 15, 45]; let sum = 0; for (let index = 0; index < arr.length; index++) { sum += arr[index]; } console.log(sum); // ๐Ÿ‘‰๏ธ 65

In this example, we achieve the same result using a basic for loop instead of a for...of loop.

It is a bit harder to read and more cluttered, however if you have to support Internet Explorer, it gets the job done.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee