Find the sum of an array of numbers in JavaScript

In this lesson, we will learn how to find the sum of an array of numbers in JavaScript.
We will look into three methods to do:

Using For Loop: Sum of array elements in JavaScript

It is a simple loop program in which we iterate through each element of an array and store it in the variable sum and finally, we print that variable.

Example:

let num = [10, 11, 12, 4, 5]
let sum = 0;
for (let i = 0; i < num.length; i++) {
sum += num[i]
}
console.log(sum)

Output:

42

Using forEach() Method to calculate the sum of the array elements

It is a built-in iterative method that calls the function on each element of the array and it can’t be executed for empty elements.

Here, we pass the function on the array.forEach Method and then that function is called upon each element.

Example:

let sum = 0;
const num = [10, 40, 12, 14];
num.forEach(myFunction);
function myFunction(element) {
sum += element;
}
console.log(sum)
Output:76

Using Reduce() Method:

It executes the specified reducer function for each element of an array resulting in a single output. It has a default value of 0 and gives an error if we work with an empty array.

The callback function takes in two values:

Accumulator: it saves the return value of the callback function

currentValue: it passes the current value

Example

const num= [10, 12, 3]
sum=num.reduce(add)
function add(accumulator, currentValue) {
return accumulator + currentValue;
}
console.log(sum);

Output:

25

These are the few ways in which we can find the sum of an array of numbers.

Leave a Reply

Your email address will not be published. Required fields are marked *