How to Calculate the Sum of Array Values in JavaScript

Calculate the Sum of Array Values in JavaScript

In JavaScript, you can sum the values in an array in more than one way to do this. From traditional loops to expressive methods like reduce(), each approach offers a slightly different perspective.

In this tutorial, we’ll explore three different ways to calculate the sum of array values. Each method includes a full code example and actual output, so you can understand the process end-to-end.

Method 1: Using reduce() – The Functional Way

The reduce() method is one of the most powerful tools in JavaScript for transforming an array into a single value. It takes a callback function and processes each item, accumulating a final result. This is often the cleanest and most elegant way to calculate a sum.

const numbers = [10, 20, 30, 40];

const sum = numbers.reduce((accumulator, num) => {
  return accumulator + num;
}, 0);

console.log("Sum of numbers:", sum);
Sum of numbers: 100

Method 2: Using a for Loop – The Traditional Approach

If you're just getting started with programming, the classic for loop might feel more familiar. It gives you complete control over how values are added up and is especially useful in educational or step-by-step scenarios.

const prices = [5, 15, 25, 10];
let total = 0;

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

console.log("Total sum:", total);
Total sum: 55

Method 3: Using forEach() – A Simple Iterative Approach

forEach() is another handy method that iterates through an array. While it doesn’t return a new value like reduce(), it allows you to perform operations on each element, making it ideal for side effects like summing values into an external variable.

const points = [2, 4, 6, 8];
let totalPoints = 0;

points.forEach(point => {
  totalPoints += point;
});

console.log("Total points:", totalPoints);
Total points: 20

When Should You Use Each Method?

If you want concise and expressive code, reduce() is the most elegant choice. It’s functional, clear, and often used in production-level JavaScript. When you’re learning or need full visibility into every step, for loops are perfect. And if you’re doing multiple things in each iteration, forEach() strikes a nice balance between clarity and control.

Comments

💬 Please keep your comment relevant and respectful. Avoid spamming, offensive language, or posting promotional/backlink content.
All comments are subject to moderation before being published.


Loading comments...