Get the sum of all the values in the array: - Javascript Array

Javascript examples for Array:forEach

Description

Get the sum of all the values in the array:

Demo Code

ResultView the demo in separate window

<!DOCTYPE html>
<html>
<body>

<button onclick="numbers.forEach(myFunction)">Test</button>

<p>Sum of numbers in array: <span id="demo"></span></p>

<script>
var sum = 0;/*w w  w .j  a va 2  s.c  om*/
var numbers = [65, 44, 12, 4];

function myFunction(item) {
    sum += item;
    demo.innerHTML = sum;
}
</script>

</body>
</html>

Related Tutorials