How to calculate sum in JavaScript?

The accumulator parameter is initially set to 0 because that's what we passed as the second argument to the Array.reduce() method.

On each iteration, we return the sum of the accumulator and the current array element.

After the last iteration, the sum variable stores the sum of the numbers in the array.

If you have to calculate the sum of arrays often, define a reusable function.

The calculateSum() function takes an array as a parameter and calculates the sum of the numbers in the array.

You can also shorten the function we passed to the reduce() method by using an implicit return statement.

The arrow function in the example uses an implicit return.

An alternative and perhaps simpler approach is to use a for...of loop.

Get the Sum of an Array of Numbers using a for...of loop

To get the sum of an array of numbers:

  1. Declare a sum variable and initialize it to 0.
  2. Use the for...of loop to iterate over the array.
  3. On each iteration, reassign the sum variable to its current value plus the value of the current element.

The for...of statement is used to loop over iterable objects like arrays, strings, reduce5, reduce6 and reduce7 objects and reduce8.

Notice that we declared the sum variable using the 00 keyword. Had we declared the variable using 01, we wouldn't be able to reassign it.

On each iteration, we reassign the sum variable to its current value plus the value of the current element.

If you have to do this often, extract the logic into a reusable function.

The calculateSum() function takes an array as a parameter, calculates the sum of its values and returns the result.

You can also use the 04 method to calculate the sum of an array.

Get the Sum of an Array of Numbers using 04

To get the sum of an array of numbers:

  1. Declare a new sum variable and initialize it to 0.
  2. Use the 04 method to iterate over the array.
  3. On each iteration, reassign the value of the sum variable to its current value plus the array element.

The function we passed to the Array.forEach() method gets called with each element in the array.

On each iteration, we reassign the value of the sum variable to its current value plus the value of the current array element.

The sum variable stores the sum of the values in the array after the last iteration.

If you have to calculate the sum of an array's elements often, define a reusable function.

The calculateSum() function takes an array as a parameter, calculates the sum of the array's elements and returns the result.

You can also use a basic accumulator2 loop to sum an array of numbers.

Get the Sum of an Array of Numbers using a accumulator2 loop

To get the sum of an array of numbers:

  1. Declare a new sum variable and initialize it to 0.
  2. Use a accumulator2 loop to iterate over the array.
  3. Reassign the value of the sum variable to its current value plus the current array element.

We used a basic accumulator2 loop to iterate over the array.

On each iteration, we use the index to access the current array element and reassign the sum variable.

Which approach you pick is a matter of personal preference. I'd use the Array.reduce() method or a for...of loop as both options are quite direct and intuitive.

In javascript, we can calculate the sum of the elements of the array by using the Array.prototype.reduce() method. The reduced method for arrays in javascript helps us specify a function called reducer function that gets called for each of the elements of an array for which we are calling that function. The output of the reduce() method is a single value that is returned as a collection of all the operations performed on each of the element of the array that is defined in the reducer function. We can use the reduce() function to retrieve the sum of all the array elements by writing a corresponding reducer function that will add the elements of the array and call this reducer function inside the reduce method.

In this article, we will learn about how sum of array elements can be calculated using the standard old way of for loop and then by the new optimized, efficient and convenient way of reducing () method along with its syntax and examples.

Old Way of the Calculating Sum of Array Elements

Before the introduction of the reduce() method, we used to calculate the sum of array elements using the for a loop. We would iterate the loop from 0 to the length of the array as indexing of the array starts from 0 and then calculate the sum inside the for a loop. Let us consider one example where we will calculate the total salary of all the employees where the salary of each employee is stored in the array salaries as shown below.

Code:

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

<!DOCTYPE html>
<html>
<body>
<p>Demonstration of using the old way of for loop for calculating sum of array elements</p>
<p id="demo"></p>
<script>
var salaries = [10000, 20000, 30000, 40000] // sums to 100000
var totalSalary = 0;
for (var i = 0; i < salaries.length; i++) {
totalSalary += salaries[i]
}
document.getElementById("demo").innerHTML = totalSalary;
</script>
</body>
</html>

that gives the following output after execution:

How to calculate sum in JavaScript?

We can see how the totalSalary variable is added with each of the value of the elements of the salaries array by iterating the for loop to retrieve the sum of the array elements that is the total salary of all the employees.

Array.prototype.reduce() Method

Now, we will learn about the reduce() method that will be used for calculating the sum of the array elements. Let us begin by studying its syntax.

All in One Software Development Bundle(600+ Courses, 50+ projects)

How to calculate sum in JavaScript?
How to calculate sum in JavaScript?
How to calculate sum in JavaScript?
How to calculate sum in JavaScript?

How to calculate sum in JavaScript?
How to calculate sum in JavaScript?
How to calculate sum in JavaScript?
How to calculate sum in JavaScript?

Price
View Courses

600+ Online Courses | 50+ projects | 3000+ Hours | Verifiable Certificates | Lifetime Access
4.6 (86,629 ratings)

array.reduce(callback( accumVariable, curValue[, index[, yourArray]] )[, valueInBeginning])
  • callback – It is also called the reducer function that is a callback or function that executes for each of the elements of the array. Note that the first value in the array is not considered if we do not supply any initial value in the valueInBeginning parameter.
  • accumVariable – It is the variable that stores the result to be returned after the reducer function is executed for all of the elements of the array. It has the value that was returned at the time of the last invocation of the reduce() method or the valueInBeginning parameter value if specified. This is the required parameter to the callback function and needs to be mentioned while using it.
  • curValue – It is a required parameter of the reducer function callback and stands for the current element of the array for which the reducer function is being executed.
  • Index – It is the index of the current element that is being processed and for which the reducer function is getting executed. It has the initial value as zero if valueInBeginning is specified else has 1 value as the initial value in it. It is optional.
  • yourArray – This is the array for which the reducer function needs to be called for each of its elements. It is an optional parameter.
  • valueInBeginning – It is the initial value that is the value that will be used as the first parameter to the function. If not specified, then the first element of the array at the zero indexes will be used as the accumulator value in the beginning and the value of the first element of the array will be skipped for the curValue variable. If the reduce method is called using the empty brackets without any parameters for a blank array without specifying the value in beginning i.e initial value then javascript will throw a TypeError.
  • Return value – The value that is returned by the reducer function/callback is a single value that is the result of the accumulation of all the values that were resulted by executing the reducer function for each of the elements of the array.

Example

Let us consider a simple example of a previous scenario where we wanted to calculate the total salary of all the employees stored in the array format. But now, we will use the reduce() method to calculate the sum instead pf for a loop as shown below.

Code:

<!DOCTYPE html>
<html>
<body>
<p>Demonstration of using Array.prototype.reduce() method for calculating sum of array elements</p>
<p id="demo"></p>
<script>
// sums to 100000
let totalSalary = [10000, 20000, 30000, 40000].reduce(function (accumVariable, curValue) {
return accumVariable + curValue
}, 0);
document.getElementById("demo").innerHTML = totalSalary;
</script>
</body>
</html>

that gives the following output after execution:

How to calculate sum in JavaScript?

Let us consider one more example where we will calculate the total expenditure where values in the array are stored in key-value pair where the key is the expenditure as shown below.

Code:

<!DOCTYPE html>
<html>
<body>
<p>Demostration of using Array.prototype.reduce() method for calculationg sum of array elements</p>
<p id="demo"></p>
<script>
// sums to 1015
let valueInBeginning = 0;
let totalExpenditure = [{expenditure: 210}, {expenditure: 152}, {expenditure: 653}].reduce(
(accumVariable, curValue) => accumVariable + curValue.expenditure
, valueInBeginning
)
document.getElementById("demo").innerHTML = "Total Expenditure = " + totalExpenditure;
</script>
</body>
</html>

that gives the following output after execution:

How to calculate sum in JavaScript?

We can find the total expenditure by using the reduced function as shown above by considering the element. expenditure value.

Conclusion

We can calculate the sum of the array elements by using the standard for loop. The most recent, optimized, and efficient way of calculating the sum of array elements is the use the reduce() method in javascript and write a reducer function or callback for it that will return the accumulated value.

This is a guide to Javascript Sum Array. Here we discuss the Introduction, Array.prototype.reduce() Method, and Old Way of the Calculating Sum of Array Elements with examples. You may also have a look at the following articles to learn more –

What is sum += in JavaScript?

The addition assignment ( += ) operator adds the value of the right operand to a variable and assigns the result to the variable.

How to calculate sum of array in JavaScript?

How to find the sum of array elements in JavaScript? To find the sum of array elements in JavaScript, you can use the array. reduce(function(total, currentValue, currentIndex, array), initialValue) method.

How to sum object values in JavaScript?

It can be as simple as that: const sumValues = obj => Object. values(obj). reduce((a, b) => a + b, 0);

How do you sum'n numbers in JavaScript?

Add n Numbers in JavaScript.
<! doctype html> <html> <body> <script> var i, n=5, sum=0; arr = new Array(10, 12, 13, 15, 19); for(i=0; i<5; i++) sum = sum + arr[i]; document.write(sum); </script> </body> </html>.
style="display:none;".
n = parseInt(document.getElementById("n"). value);.
document. ... .
temp. ... .