There are multiple ways that you should use in order to calculate the sum of an array of numbers. Let’s discuss each of them and try examples.
You can use the reduce() method to find the sum of an array of numbers.
The reduce() method executes the specified reducer function on each member of the array resulting in a single output value as in the following example:
The 0 in is the default value. If default value is not supplied, the first element in the array will be used. If the array is empty, you will get an error.
If you use ES2015, you can make it more verbose like this:
Another fast method is using for loop which is even faster as the reduce() method:
An alternative way of calculating the array of numbers is using forEach loop like this:
The reduce() method invokes a reducer function provided on each element of the array and results in single output value. It executes the callback once for each assigned value present in the array taking four arguments: accumulator, currentValue, currentIndex, array. It is recommended to provide default value such as 0 for performing addition and 1 for performing multiplication.