Javascript Data Type How to - Use forEach function to add the values of any sized array








Question

We would like to know how to use forEach function to add the values of any sized array.

Answer


<!DOCTYPE html>
<html>
<head>
<!-- w  w w . j a  va2  s  .co  m-->
<script type='text/javascript'>

var array = [1,3,4,5,2,10];
var sumOfArray = 0;
array.forEach(function(value,index){
    sumOfArray = sumOfArray + value;
});
document.writeln(sumOfArray);

</script>
</head>
<body>
</body>
</html>

The code above is rendered as follows: