Sling Academy
Home/JavaScript/JavaScript: 6 Ways to Calculate the Sum of an Array

JavaScript: 6 Ways to Calculate the Sum of an Array

Last updated: February 19, 2023

This practical, succinct article walks you through three examples that use three different approaches to find the sum of all elements of a given array in Javascript (suppose this array only contains numbers). Without any further ado, let’s get started.

Using Array.reduce() method

If you’re using modern Javascript (ES6 and beyond), this might be the neatest and quickest solution.

Example:

// define a reusable function
const calculateSum = (arr) => {
    return arr.reduce((total, current) => {
        return total + current;
    }, 0);
}

// try it
console.log(calculateSum([1, 2, 3, 4, 5]));

Output:

15

The reduce() method executes a reducer function for elements of an array. It returns the accumulated result from the last call of the callback function. Below is the syntax:

array.reduce(function(total, current, index, arr), initialValue)

Where:

  • total (required): The initial value, or the previously returned value of the function
  • current (required): The current element
  • current (optional): The index of the current element
  • arr (optional): The array that the current element belongs to

Javascript is interesting, and it also has another method quite similar to the reduce() method, named reduceRight(). You can get the sum of a numeric array with only a single line of code like this:

const sum = [1, 2, 3, 4, 5].reduceRight((acc, cur) => acc + cur, 0);
console.log(sum);

Output:

15

Using a classic For loop

This is an easy-to-understand approach and has been used for decades. However, the code is a bit longer.

Example:

// define a reusable function
function calculateSum(arr) {
    var sum = 0;
    for (var i = 0; i < arr.length; i++) {
        sum += arr[i];
    }
    return sum;
}

// try it
console.log(calculateSum([1, 2, 3, 4]));

Output:

10

Using modern For/Of loop

This approach also uses a loop but is more concise than the previous one. Like the Array.reduce() method, for/of was added to ES6 (JS 2015).

Example:

const arr = [9, 8, 7, 6, 5];
let sum = 0;
for (let e of arr){
    sum += e;
}
console.log(sum);

Output:

35

Using the map() method

The Array.map() method is new in ES6 and beyond. This one is very useful when you have to deal with an array, including finding the sum of its elements.

Example:

const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];

let sum = 0
arr.map(e => sum += e)
console.log(sum);

Output:

66

Using a While loop

Another way to sum the elements of an array for your reference (basically, it’s quite similar to other methods of using loops).

Example:

const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

let sum = 0;
let i = -1;
while (++i < arr.length) {
  sum += arr[i];
}
console.log(sum);

Output:

55

Using a forEach loop

Just another kind of loop in Javascript. Here’s how to make use of it to calculate the total value of a given array:

const array = [1, 2, 3, 4];

let sum = 0;
array.forEach(e => {
  result += e;
})

console.log(result);

Output:

10

Conclusion

We’ve walked through several ways to get the sum of all elements of a given array in Javascript. Although just one method is enough, knowing the existence of other methods also helps you a lot in mastering the art of programming. Good luck and happy coding!

Next Article: JavaScript: 5 Ways to Concatenate Multiple Arrays

Previous Article: The Modern JavaScript Arrays Cheat Sheet

Series: Working with Arrays in JavaScript

JavaScript

You May Also Like

  • Handle Zoom and Scroll with the Visual Viewport API in JavaScript
  • Improve Security Posture Using JavaScript Trusted Types
  • Allow Seamless Device Switching Using JavaScript Remote Playback
  • Update Content Proactively with the JavaScript Push API
  • Simplify Tooltip and Dropdown Creation via JavaScript Popover API
  • Improve User Experience Through Performance Metrics in JavaScript
  • Coordinate Workers Using Channel Messaging in JavaScript
  • Exchange Data Between Iframes Using Channel Messaging in JavaScript
  • Manipulating Time Zones in JavaScript Without Libraries
  • Solving Simple Algebraic Equations Using JavaScript Math Functions
  • Emulating Traditional OOP Constructs with JavaScript Classes
  • Smoothing Out User Flows: Focus Management Techniques in JavaScript
  • Creating Dynamic Timers and Counters with JavaScript
  • Implement Old-School Data Fetching Using JavaScript XMLHttpRequest
  • Load Dynamic Content Without Reloading via XMLHttpRequest in JavaScript
  • Manage Error Handling and Timeouts Using XMLHttpRequest in JavaScript
  • Handle XML and JSON Responses via JavaScript XMLHttpRequest
  • Make AJAX Requests with XMLHttpRequest in JavaScript
  • Customize Subtitle Styling Using JavaScript WebVTT Integration