How to get the sum of an array elements in JavaScript?

To get the sum of an array elements in JavaScript, you can use the array.reduce(callback, initialValue) method. The reduce() method allows you to call the callback function once for each array element in ascending index order (left to right). The reduce() method returns a single value: the result of the last callback function call. The range of elements processed by the reduce() method is set before the first call to the callback function. If elements were added to the array after it was called, then the function will not be called on such elements. If the array has only one element (regardless of position) and no initialValue is specified, or if initialValue is provided, but the array is empty, then the value of that element will be returned without calling the callback. You can also find the sum of an array in JavaScript with a "for" loop. In this JavaScript Array Sum Example, we use the reduce() method to get the sum of the array elements. Below you can see more examples of calculating the sum of a JavaScript array with detailed descriptions. Click Execute to run the JavaScript Array Sum Example online and see the result.
Loading...