Get the Sum of an Array of Numbers in JavaScript


So you need to calculate the sum of an array of numbers in Javascript. So, lets see how its done:


Using a For…of Loop

Let’s start with a simple and elegant solution using a for…of loop. This loop allows you to iterate through each element of the array, making it a beginner-friendly approach. Here, we declare a variable sum, initialize it to 0, and add each element of the array to it using the for…of loop.

JavaScript
let numbers = [1, 2, 3, 4, 5];
let sum = 0;

for (let num of numbers) {
  sum += num;
}

console.log("The sum is:", sum);

Using Array.forEach()

Another method involves using the forEach() method provided by the Map object. This approach offers a cleaner and more functional style of iterating over Map entries. The forEach method takes a callback function that is executed for each element, updating the sum accordingly.

JavaScript
let numbers = [1, 2, 3, 4, 5];
let sum = 0;

numbers.forEach(function (num) {
  sum += num;
});

console.log("The sum is:", sum);

The forEach() method simplifies the iteration process, and the provided callback function handles the summation logic.

Using a for Loop

Old but gold, the traditional for loop also gets the job done. The for loop here iterates through the array and adds each element to the sum.

JavaScript
let numbers = [1, 2, 3, 4, 5];
let sum = 0;

for (let i = 0; i < numbers.length; i++) {
  sum += numbers[i];
}

console.log("The sum is:", sum);

Using a While Loop

If you’re a fan of while loops, you can use one to achieve the same result. This while loop increments i until it reaches the length of the array, summing up the numbers.

JavaScript
let numbers = [1, 2, 3, 4, 5];
let sum = 0;
let i = 0;

while (i < numbers.length) {
  sum += numbers[i];
  i++;
}

console.log("The sum is:", sum);

Using Reduce

Reduce allows us to reduce an array to a single value – in our case, the sum.

JavaScript
let numbers = [1, 2, 3, 4, 5];
let sum = numbers.reduce(function (accumulator, currentValue) {
  return accumulator + currentValue;
}, 0);

console.log("The sum is:", sum);

In the reduce method, the accumulator is a variable that accumulates the results of each iteration. In our case, it’s the running total of the sum. The currentValue represents the current element being processed. The initial value (0 in our example) sets the starting point for the accumulator.

On each iteration, the sum variable is reassigned with its current value plus the value of the current array element. This dynamic update is a key concept, and it makes reduce a concise and elegant solution for array operations.

const vs let

Notice that we declared the sum variable using the let keyword. Why not const? Well, if we had used const, we wouldn’t be able to reassign it. In the context of our problem, reassignment is crucial as we update the sum on each iteration. So, remember, when the value needs to change over time, let is your go-to choice.


🧪Practice Coding Problem: The Reverse Sum

In the spirit of Test Driven Development ( 😁), lets test our understanding by solving a problem.

You’ve encountered an quirky array. Each element is a string representing a number, but there’s a twist – the digits are reversed. Your task is to create a function that takes this array as input, reverses the digits of each element, converts them back to numbers, and returns the sum of these numbers.

JavaScript
/**
 * Calculates the sum of reversed digits in an array.
 * @param {string[]} array - An array of strings representing reversed digits.
 * @returns {number} - The sum of the numbers after reversing the digits.
 */
function unusualSum(array) {
  // > > > 👉 Write code here 👈 < < <  
}

// Example usage:
const inputArray = ["21", "43", "56"];
const result = unusualSum(inputArray);
console.log("The unusual sum is:", result);
Please attempt before seeing the Answer:
JavaScript
function unusualSum(array) {
  let sum = 0;

  for (let reversedNumber of array) {
    // Reverse the digits and convert back to a number
    const originalNumber = parseInt(reversedNumber.split("").reverse().join(""));
    
    // Add the number to the sum
    sum += originalNumber;
  }

  return sum;
}

Explanation:

  • The for…of loop is used to iterate through each element in the array, which represents a string with reversed digits.
  • Within the loop, split("") is used to convert the string into an array of characters, reverse() reverses the order of the characters, and join("") converts the array back to a string with reversed digits.
  • parseInt() is then used to convert the reversed string back to a number.
  • The original numbers are added to the sum variable.
  • The final sum is returned.

Hopefully, with these techniques under your belt, no JavaScript array shall remain unsummable. 😎

Keep coding🚀!

Scroll to Top