Use the reduce() inbuild method to get the sum of an array in JavaScript. This method reduces the array to a single value.
Note:
- The method will not execute the function for array elements without values.
- This method does not change the original array.
Example of JavaScript sum array
Here is demonstrated HTML example code of JavaScript sum array. If the array is empty and no initialValue is provided, an error will be thrown.
<!DOCTYPE html>
<html>
<head>
<script>
var array = [1, 2, 3, 4, 5];
// Getting sum of numbers
var sum = array.reduce(function(a, b){
return a + b;
}, 0);
alert(sum);
</script>
</head>
<body>
</body>
</html>
Output:
Do comment if you have any questions and doubts on this topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version