How to Find Sum of Array of Numbers in JavaScript

JavaScript developers heavily depend on arrays to store numbers and text. JS arrays are easy to use, allow you to store data in a compact manner and offer many useful methods out of the box. Often web developers need to be able to sum all the items of an array. There are several ways to do this in JavaScript. In this article, we will learn how to find sum of array of numbers in JavaScript.

How to Find Sum of Array of Numbers in JavaScript

Here are some of the most common ways to find sum of array of numbers in JavaScript.

1. Using for loop

This is the simplest way to sum items in an array. We initialize the sum of array to zero in a variable. Then we run a for loop over the array items and in each iteration we add the item to the sum. By the time the for loop exits, the sum variable will contain the value of sum of array items.

Here is an example to illustrate it.

var array = [1, 2, 3, 4, 5];
var sum = 0;
for (i = 0; i < array.length; i++) {
sum += array[i];
}
console.log(sum); // output is 15

This method is very easy to understand and applicable for all arrays. You can also selectively choose the items you want to include/exclude in the sum, by adding custom conditions in each iteration. Here is an example to sum only even numbers in an array.

var array = [1, 2, 3, 4, 5];
var sum = 0;
for (i = 0; i < array.length; i++) {
if(array[i]%2 == 0){
sum += array[i];
}
}
console.log(sum); // output is 6

If your data contains non-numerical items then you can call a custom function to use 0 in its place, in every iteration. Here is an example where define a function isnum() to simply check if a variable is a number or not. If it is not a number, the function returns 0, else it returns the number itself.

var array = [1, 'a', 3, 'b', 5];
var sum = 0;
function isnum(n){
return isNaN(n) ? 0 : n;
}
for (i = 0; i < array.length; i++) {
sum += isnum(array[i]);

}
console.log(sum); // output is 9

You can always define a function that accepts an array as an input argument and runs a for loop to calculate the sum of its elements.

var a = [1, 2, 3, 4, 5];
function sum(array){
var sum = 0;
for (i = 0; i < array.length; i++) {
sum += array[i];
}
return sum;
}
console.log(sum(a)); // output is 15

You may also use other loop constructs like while to loop through the array and find sum of its elements.

2. Using forEach() method

Every JS array supports a built in method forEach() that can be called directly from the array. It allows you to define and call custom function for each item of the array. For example, you can initialize sum variable to 0 and use forEach() to loop through the array and sum each item to sum variable. Here is an example to demonstrate it.

var array = [1, 2, 3, 4, 5];
var sum = 0;
array.forEach(x => {
sum += x;
});

console.log(sum);

If you are not comfortable with using arrow functions as shown above, then you can also use traditional functions.

var total = 0;
var array = [1, 2, 3, 4, 5];

function my_sum(item) {
total += item;
}
array.forEach(my_sum);

console.log(total);

In the above code, we have defined a JS function my_sum() that accepts an item and adds it to the total variable. We call this function in forEach() method. In this case, forEach() will run a loop over the items of array, and call my_sum() function on each item.

3. Using reduce() function

Every array also supports reduce() method that loops through the array and applies a reducer function to each item of the array. While doing so, it accumulates the result of each iteration and makes it available to the next iteration. Finally, it returns a single value. It does not run for empty arrays.

var array = [1, 2, 3, 4, 5];

let sum = array.reduce(function (x, y) {
return x + y;
}, 0);

console.log(sum); // output is 15

In the above code, we define a function that adds 2 variables and returns the result. But it works differently than what is obvious. Initially, it adds the first 2 items and stores its result. In the next iteration, it adds the next item, that is, the 3rd item to this stored result, and so on. When it has gone through all items one by one, and added them to the result, it returns the result, which is stored in sum variable.

The default sum or result is specified as 0, the second argument of reduce(). The first argument is the reducer function itself. If you do not specify the default value, then reduce() function will return undefined as the final result.

Reduce method is similar to forEach except a few key differences. Reduce function specifically aggregates the values of an array and returns a single value in the end. forEach executes a specific function for each item of the array and does not return anything. Basically, reduce() function was created to reduce the array to a single value and return it.

Compared to forEach(), using reduce() is faster and results in more compact code. This is because reduce() is specifically designed for aggregation and optimizes order of aggregation. On the other hand, forEach() will sequentially go through the array items, instead of using any other order.

4. Using recursion

Recursion is when you call a function inside its own definition, until it reaches a state where it cannot be called anymore. Here is an example to use a simple recursive function to sum items of array.

var array = [1, 2, 3, 4, 5];
function sum(a, i) {
if (i === array.length) {
return 0;
}
return a[i] + sum(a, i + 1);
}
console.log(sum(array, 0));

In the above code, we define a function sum() that accepts an array and starting index=0. In each call, it returns the sum of array item present at index and the result of sum() function called on array along with index incremented by 1. This goes on until the index is equal to array’s length, that is, beyond the array items. At this point, it returns 0 and does not call sum() function any further.

Please note, recursive functions are a little difficult to understand and also take up more memory, since each function call will need its own memory stack space. Also, if you do not define the termination condition of recursive function correctly, then it may forever keep calling the function one inside the other and crash.

Conclusion

In this article, we have learnt several ways to find sum of array of numbers in JavaScript. We learnt how to add up all items of an array using a simple for loop. We also learnt how to do it using forEach() as well as reduce() functions. Lastly, we learnt how to find sum of array of numbers using recursion. We have covered several important use cases in each of these solutions. You can use any of these methods as per your requirement.

Also read:

How to Search Object in Array of Objects
How to Add New Elements to Beginning of JS Array
How to Get Unique Values in JavaScript

Leave a Reply

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