Sum of Array in JavaScript

An array is a data structure that serves the purpose of keeping a collection of various types of data under a single variable identifier.

At times, it becomes necessary to calculate the total of arrays. In this article, we will explore how to compute the sum of an array in JavaScript. While JavaScript does not offer a dedicated built-in function specifically for summing an array, there are several techniques available that we can utilize to achieve this task.

Following are the methods used to sum an array in JavaScript:

  • reduce method
  • forEach method
  • for loop
  • for…of loop
  • Lodash _.sum Method
  • Recursion
  • map and reduce methods

Let’s explore these techniques individually through demonstrations.

reduce method

This method was introduced in ECMAScript 6.

Syntax:

Example

array.reduce(function(total, current_value, current_index, arr), initial_value)

In the syntax presented above, the parameters outlined below are discussed:

function(total, currentValue, currentIndex, arr): This is a function that is invoked for every element in the array.

total: This parameter is employed to hold the cumulative result. It contains the value returned from the last invocation of the reduce method. Being a required parameter, it is essential that we provide it.

current_value: This denotes the value of the present element, which is the element that the reduce function is currently processing. Furthermore, it is a required parameter.

currentindex: This denotes the value of the current index at which the reduce function is operating. When an initial value is specified, the currentindex will start at 0; if no initial value is provided, it will begin at 1. This parameter is optional.

initialvalue: This denotes the starting value assigned to the function. It is an optional argument. In the absence of a specified initial value, the first element of an array is treated as the total value at the outset, and this value will not be counted as currentvalue.

Demonstration:

In this demonstration, we will develop a program that calculates the total of an array by employing the reduce method.

Code:

Example

<!DOCTYPE html>
<html lang ="en">
<head>
  <title>Sum of an array in JavaScript using the reduce() method</title>
</head>
<body>
<h3>Sum of an array is given below:</h3>
<p id="sum"></p>
<script>
var numbers = [12, 14, 16, 18];
var Sum = 0;
const reducer = (total, current_value) => total + current_value;
Sum = numbers.reduce(reducer);
document.getElementById("sum").innerHTML = Sum;
</script>
</body>
</html>

Output:

The result displayed below demonstrates the computation of the sum of an array using the reduce method.

forEach method

This approach is employed to invoke a function for each element within the array, which is utilized for computing the sum of an array in JavaScript.

Syntax:

Example

array.forEach(function(current_value, current_index, arr), thisValue)

In the syntax presented above, the parameters listed below are elaborated upon:

function(current_value, index, arr): This function is executed for every element present in the array. It represents the value that is needed.

current_value: This refers to the value of the element that is currently in focus. It represents the value that is needed.

current_index: This parameter specifies the index number of the element currently being processed. It is an optional parameter.

arr: This refers to the array associated with the current element. It is considered an optional parameter.

thisValue: This refers to the value that is provided to the function to serve as the "this" context within it. It is considered an optional parameter. In cases where it is not defined, the default value assigned will be undefined.

Demonstration:

We are going to develop a program that calculates the total of an array by employing the forEach method.

Code:

Example

<!DOCTYPE html>
<html lang ="en">
<head>
  <title>Sum of an array in JavaScript using the forEach() method</title>
</head>
<body>
<h3>Sum of an array is given below:</h3>
<p id="sum"></p>
<script>
var numbers = [55, 60, 65, 70]
var Sum = 0;
numbers.forEach(item => {
    Sum += item;
 });
document.getElementById("sum").innerHTML = Sum;
</script>
</body>
</html>

Output:

In the following output, we can observe the calculation of the sum of an array performed using the forEach method.

for loop

The total of an array can be determined using a for loop, which is employed to traverse the array starting from index 0 all the way to the final index of the array.

Syntax:

Example

for (expression 1; expression 2; expression 3) {
  // code block which is to be executed
}

Demonstration:

We will develop a program that calculates the total of an array by employing a for loop.

Code:

Example

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Sum of an array in JavaScript using for loop</title>
  </head>
<body>
<p>Sum of array elements is provided below:</p>
<p id="sum"></p>
<script>
    var numbers = [100, 200, 300, 400]
    var Sum = 0;
    for (var j = 0; j < numbers.length; j++) {
        Sum += numbers[j]
    }
    document.getElementById("sum").innerHTML = Sum;
</script>
</body>
</html>

Output:

Below is the result demonstrating the computation of an array's sum through the use of a for loop.

for…of loop

This loop is employed to iterate over the elements of iterable objects.

Syntax:

Example

for (variable of iterable) {
  // code block which is to be run
}

The above syntax is discussed below:

A variable can be established utilizing the keywords const, var, or let. After each iteration, the variable is assigned the value from the subsequent iteration.

iterable: This refers to an object that possesses iterable characteristics.

Demonstration:

We are going to develop a program that calculates the total of an array by employing a for…of loop.

Code:

Example

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Sum of an array in JavaScript using for..of loop</title>
  </head>
<body>
<p>Sum of array elements is given below:</p>
<p id="sum"></p>
<script>
let numbers = [50, 55, 60, 65, 70];

let sum_result = 0;

for (let number of numbers) {
  
  sum_result += number;
}
document.getElementById("sum").innerHTML = sum_result;
</script>
</body>
</html>

Output:

Below is the output showcasing the computation of an array's total using the for…of loop.

Lodash _.sum Method

Lodash is a built-in library in JavaScript that features a method known as ".sum". This method can be employed to calculate the total of the numerical values contained within an array.

Demonstration:

We are going to develop a program that calculates the sum of an array by employing the .sum function from Lodash.

Code:

Example

var _ = require('lodash');
var values = [1, 2, 3, 4, 5];
var result = _.sum(values);
console.log(result);

Output:

Below is the result where we observe the total of an array computed using the Lodash .sum function.

Recursion

This is a recursive function that repeatedly invokes itself until every element within the array has been addressed.

Demonstration:

We are going to develop a program that calculates the sum of an array using a recursive approach.

Code:

Example

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Sum of an array in JavaScript using recursion</title>
  </head>
<body>
<p>Sum of array elements is given below:</p>
<p id="sum"></p>
<script>
let arr = [5, 6, 50, 11, 25, 39];

function sumArray(arr, index) {
    if (index === arr.length) {
        return 0;
    }
    return arr[index] + sumArray(arr, index + 1);
}

document.getElementById("sum").innerHTML = sumArray(arr, 0);
</script>
</body>
</html>

Output:

Presented below is the output showcasing the computation of the sum of an array achieved through the use of recursion.

map and reduce methods

The methods map and reduce are employed for the purpose of aggregating an array. The map method generates a new array by applying the callback function to each element of the original array, while the reduce method consolidates this new array into a single value by also utilizing a callback function.

Demonstration:

We are going to develop a program that calculates the sum of an array using a recursive approach.

Code:

Example

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Sum of an array in JavaScript using both map() and reduce() methods</title>
  </head>
<body>
<p>Sum of array elements is given below:</p>
<p id="sum"></p>
<script>
let numbers = [106, 107, 108, 109, 110];

let sum = numbers.map(number => number * 1)
    .reduce((accumulator, current) => accumulator + current);

document.getElementById("sum").innerHTML = sum;
</script>
</body>
</html>

Output:

The following output demonstrates the computation of the sum of an array using the map and reduce functions.

Conclusion:

In the preceding article, we explored various techniques for computing the sum of an array in JavaScript. We examined multiple approaches accompanied by examples, including the reduce function, the forEach function, the traditional for loop, the for…of loop, the Lodash _.sum function, recursion, as well as the combination of map and reduce functions.

Input Required

This code uses input(). Please provide values below: