JavaScript

How to find the sum of an array of numbers in javascript

Arrays can store multiple elements of a single data type like an array of strings comprise values of string data types. Similarly, the array of numbers refers to storing the numeric values inside an array. JavaScript provides various methods that can be used to perform operations on arrays. In this informative post, we have compiled various possibilities to sum an array of numbers. By the end of this guide, you will get an understanding of the following methods:

How to use for loops to sum an array of numbers

The iterative nature of the for loop helps to sum all the numbers of an array. Before getting into examples, let’s understand the working of for loop in JavaScript.

for(initialization; condition; increment/decrement){
statement 1;
statement 2;
}

The initialization of the variable sets the value from where the loop variable will start. The condition part of the for loop sets a threshold that must be fulfilled to execute statements (JavaScript code). After each iteration, the increment/decrement part increases or decreases the value of the loop variable.

Example
The JavaScript code provided below makes use of a for loop to sum the elements of an array.

var arr1 =[2, 20, 40, 100];
var res = 0;
for (i=0; i < arr1.length; i++) {
     res += arr1[i]
}
console.log(res);

The above code creates an array of numbers named arr1. The res variable is initialized to store the sum of elements. After that, the for loop is exercised in the following manner:

  • the variable “i” is initialized at “i=0
  • the looping condition is “i < arr1.length” which states that the loop will run until the value of “i” is less than the length of arr1. After each iteration, the value of “i” would be incremented by “1“.
  • the statement inside the for loop updates the value of the res variable after each iteration by adding the array element in it

Output

The output shows that the numbers inside the array are summed up and the sum is printed.

How to use a while loop to sum an array of numbers

The working of while-loop depends on the following syntax.

While (condition) {
Statement(s) of code;
Increment/decrement;
}

Once a condition is checked, the code is executed until it is true. A final increment or decrement of the variable concludes the iteration.

Example

The following JS code practices a while-loop to sum an array of numbers.

var arr =[2, 4, 8, 14];
var sum = 0;
var i=0;
while (i < arr.length) {
     sum += arr[i]
     i++;
}
console.log(sum);

In the above code, the array named arr is initialized alongside the variables named “sum” and “i“. Moreover, the condition is set to “i < arr.length” which states that the while loop will run until the value of variable “i” reaches the length of arr. Inside the loop, each array element would be summed up to the value of sum.

Output

The above output shows that the while loop can be used to sum an array of numbers in JavaScript.

How to use reduce() method to sum an array of numbers

The array reduce() method of JavaScript can also be used to sum the array of numbers. Like for loop, the reduce() method also iterates over the numbers of an array. The syntax followed by the reduce() method is provided below.

array.reduce(function(RetVal, CurrVal, CurrIndex, array), Val)

The reduce() method accepts two parameters, first if callback-function and the second is Val(initial value). The callback-function can accept four parameters, two (RetVal and CurrVal) of them are necessary and other two (CurrIndex and array) are optional.

Example

The following JavaScript code makes use of the reduce() method to calculate the sum of the numbers stored in an array.

var arr = [4, 8, 12, 16];
function sum(total, curr) {
    return total + curr;
  }
console.log(arr.reduce(sum, 0));

In the above code,

  • An array of numbers is initialized named arr
  • Callback-function (sum) is exercised which contains two parameters total and curr. The total represents the last value returned by the sum function and the curr value refers to the element of the array.
  • Lastly, the reduce(sum, 0) is applied to iterate the sum function over each element of the array.

Output

The output shows that the reduce() method has calculated the sum of the array of numbers.

Conclusion

JavaScript provides the support of various loops(e.g. “for” and “while”) and the reduce() method to sum an array of numbers. The iterative nature of loops is helpful in getting the sum of an array because the loops intend to consider each element one by one. To get the sum of array elements in JavaScript, we have provided the syntax and usage of for-loop, while-loop, and reduce() method to add all the numbers of an array.

About the author

Adnan Shabbir