top of page
Writer's pictureThe Tech Platform

Different ways to get the sum of arrays in JavaScript?

Updated: Aug 22, 2022

In JavaScript, array is a single variable that is used to store different elements. It is often used when we want to store list of elements and access them by a single variable. Unlike most languages where array is a reference to the multiple variable, in JavaScript array is a single variable that stores multiple elements.


Flowchart:



1. For Loop

The for loop is used to iterate an array. We can use it to add all the numbers in an array and store it in a variable.


Example:

var arr =[-10, 6, 11, 24];
var sum = 0;
var i=0;
 for (let i = 0; i < arr.length; i += 1) {
    sum += arr[i];
  }
  
console.log("The array is :",arr);
console.log("The sum of array using while loop is :",sum);


Output:





2. Foreach

forEach is a built-in or array-like method.


Example:

var arr =[6, 9, -4, 14];
var sum = 0;
var i=0;
 arr.forEach(item => {
    sum += item;
  });
console.log("The array is :",arr);
console.log("The sum of array using while loop is :",sum);


Output:





3. While Loop

The while statement creates a loop that executes a specified statement as long as the test condition evaluates to true. The condition is evaluated before executing the statement.


Example:

var arr =[2, 4, 8, 14];
var sum = 0;
var i=0;
while (i < arr.length) {
     sum += arr[i]
     i++;
}
console.log("The array is :",arr);
console.log("The sum of array using while loop is :",sum);

Output:



4. For..of

for...of lets us iterate over an array, so we can make use of it to get the sum of an array. Since we keep the same style of functions as above, let’s copy and adjust.


Example:

var arr =[2, 9, 24, -14];
var sum = 0;
var i=0;
for (const item of arr) {
    sum += item;
  }
  
console.log("The array is :",arr);
console.log("The sum of array using For...of is :",sum);

Output:




The Tech Platform

0 comments

Comments


bottom of page