Javascript: 3 Ways to Calculate the Sum of an Array

Last updated on June 23, 2022 A Goodman Loading... One comment

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

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

Conclusion

You’ve learned more than one technique to totalize all elements of a numeric array in Javascript. Keep the ball rolling and continue exploring more new and awesome stuff in the modern Javascript world by taking a look at the following articles:

You can also check out our Javascript category page, TypeScript category page, Node.js category page, and React category page for the latest tutorials and examples.

Subscribe
Notify of
guest
1 Comment
Inline Feedbacks
View all comments
Thales
Thales
2 months ago

how can i sum an array but the array has a string element inside it???

Related Articles