How To Get The Sum Of An Array Of Numbers In JavaScript

How To Get The Sum Of An Array Of Numbers In JavaScript

There are multiple ways to get the sum of an array of numbers in JavaScript. Learn more about them below.

Get The Sum Of An Array Of Numbers In JavaScript

With ‘for’ Loops

Assume we have an array that stores the numbers of visitors to LearnShareIT.com each month for the first half of 2022:

let visitors = [123034, 149340, 175429, 154034, 122484, 148595];

Now we want to get the total number during that period. The most straightforward solution is using a for loop.

Note: follow this guide if you want to create an array containing numbers from 1 to n.

The basic idea is that we run through every element of the array and add its value to a variable used for this accumulation. The final value of that variable is the sum we are looking for.

This algorithm pretty much works with every programming language and doesn’t require you to know any advanced techniques of JavaScript. Just the basic syntax of loops and iteration should be enough.

This is how you can get this done in JavaScript with a simple for loop and the addition assignment operator (+=):

let visitors = [123034, 149340, 175429, 154034, 122484, 148595];
let sum = 0;

for (let i = 0; i < visitors.length; i += 1) {
    sum += visitors[i];
}

console.log(sum);

Output:

872916

We must declare a variable to hold the intermediate and final sums, and its initial value must be zero. A JavaScript for loop has similar syntax and works in a similar way to its C and Java counterparts:

for ([initialExpression]; [conditionExpression]; [incrementExpression]) {statement}

You must provide an initialization expression to initialize our loop counter (the variable i). The second expression (conditionExpression) specifies how the loop will be terminated.

In this case, JavaScript will exit the loop when the counter is equal to the length of the array. Since the first index is zero, this means the for loop will end just after it adds the final element to the sum. The final expression (incrementExpression) tells the loop how it should update the counter after it executes the statement.

With forEach()

The forEach() method runs a function (given by you) once for each element of an array. You can use it to replace the for loop above:

let visitors = [123034, 149340, 175429, 154034, 122484, 148595];
let sum = 0;
visitors.forEach(element => sum += element);
console.log(sum);

Output:

872916

This is a simple form of forEach(), where we only need an array function to define the code we need to run on every element:

forEach((element) => { /* … */ })

In addition to element, you can also use other arguments, such as ‘index’, when necessary. Remember that the forEach() method iterates through the array in ascending index order. It also only executes the callback function on indexes that have been assigned to values.

With Array.reduce()

The reduce() method allows you to execute a callback function on every element of an array. When the function goes through an element, its returned value will be passed to the next element.

You can use this method to go through the array element-by-element and add the current element to the sum variable:

let visitors = [123034, 149340, 175429, 154034, 122484, 148595];
let init = 0;

const sum = visitors.reduce(
	(previous, current) => previous + current,
	init
);

console.log(sum);

Output:

872916

In this example, we use an array function to define a simple function. The job of this function is to add the returned value of the previous call to the value of the current element.

Summary

In addition to a simple for loop, you can also use forEach() and reduce() to get the sum of an array of numbers in JavaScript. They are built-in methods that can run a callback function on all elements of an array.

Maybe you are interested:

Leave a Reply

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