Get the Sum of an Array of Numbers in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

Get the Sum of an Array of Numbers #

To get the sum of an array of numbers:

  1. Use the Array.reduce() method to iterate over the array.
  2. Set the initial value in the reduce method to 0.
  3. On each iteration, return the sum of the accumulated value and the current number.
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 argument to the reduce method.

On each iteration, we return the sum of the accumulator and the current array element.

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 and initialize it to 0.
  2. Use the for...of loop to iterate over the array.
  3. On each iteration, reassign the sum variable to its current value plus the value of the current element.
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 declared 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 reassign the sum variable to its current value plus the value of the current element.

You can also use a basic for loop to sum an array of numbers.

index.js
const arr = [5, 15, 45]; let sum = 0; for (let index = 0; index < arr.length; index++) { sum += arr[index]; } console.log(sum); // 👉️ 65

This example achieves the same goal, but instead of using for...of we used a basic for loop.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.