This post will discuss how to calculate the sum of all the values in an array in JavaScript.

1. Using Array.reduce() function

The Array.reduce() function in Java is used to call a reducing function on each array element, and accumulating the results in a single value. We can calculate the sum of all array values by using a reducer function that adds the current element’s value to the already computed sum of the previous values. This is demonstrated below using an anonymous function:

Download  Run Code

2. Using Lodash Library

Another alternative to find the sum of all values in an array is using the _.sum function from the lodash library. This function takes an array of numbers as an argument and returns the sum of all the elements present in the array. The following code example demonstrates its usage:

Download Code

3. Using a loop

A naive solution is to use a loop for iterating over the array elements and keeping track of the sum in a variable. The variable is updated with the current element’s value in each iteration of the loop. The loop can be either a for loop, an enhanced for loop, or forEach() function. The following code demonstrates this:

Download  Run Code

That’s all about calculating the sum of all values in an array in JavaScript.