Sum of array JavaScript
In this post, you will learn how to find the sum of array using the JavaScript.
An array is a collection of key-value pairs. We can store more than one item in a single variable, i.e., an array. So, an array is used when there is a requirement to add more items in a single variable. A JavaScript array is treated like a global object that is used to create an array. Here, we have used different ways to find the sum of all elements of the given array using JavaScript.
JavaScript find the Sum of an Array using for loop
In the given JavaScript program, we have used the for loop to find the sum of an array.
// Defining array
var arr = [44, 3, 5, 8]
// variable to store the sum
var sum = 0;
// calculating sum using the for loop
for (let i = 0; i < arr.length; i++) {
sum += arr[i];
}
console.log("Sum of array elements: " + sum);
Output of the above code:
Sum of array elements: 60
JavaScript find the Sum of an Array using forEach
The forEach() method of JavaScript calls a function and iterates over the elements of an array. Here, we have used this method to calculate the sum of an array.
// Defining array
var arr = [14, 8, 2, 8]
// variable to store the sum
var sum = 0;
// calculating sum using the forEach
arr.forEach(x => {
sum += x;
});
console.log("Sum of array elements: " + sum);
Output of the above code:
Sum of array elements: 32
JavaScript find the Sum of an Array using reduce() method
The reduce() method executes a reducer function on each element of the array and returns a single output value.
The value you return from this function will be the accumulatedValue used for the next iteration of the reduce() method. For the first iteration, the accumulatedValue will be assigned with the value at index zero. When the iteration is finished, the reduce() method will return a single value, which is the accumulatedValue. Here, we have used this function to find the sum of an array.
// Defining array
var arr = [10, 8, 2, 8, 7]
// Calculating sum
var sum = arr.reduce(function (x, y) {
return x + y;
}, 0);
console.log("Sum of array elements: " + sum);
Output of the above code:
Sum of array elements: 35
Related Articles
Generate random numbers in JavaScriptJavascript window location
Remove duplicates from array Javascript
Scientific calculator JavaScript
How to reverse string in Javascript
JavaScript display PDF in the browser using Ajax call
Parsing JSON in Javascript
Javascript speech recognition example
Select/deselect all checkboxes using Javascript
Print specific part of a web page in javascript
Dynamically Add/Delete HTML Table Rows Using Javascript
jQuery Ajax serialize form data example
Image popup on page load using HTML and jQuery
Ajax live data search using jQuery PHP MySQL
jQuery loop over JSON result after AJAX Success
Simple star rating system using PHP, jQuery and Ajax
jquery image zoom on mouseover example
Bootstrap star rating input example
Bootstrap datepicker example
Submit a form data without page refresh