find the sum of all elements in an array in Javascript
Code snippet on how to find the sum of all elements in an array in Javascript
function sumArray(arr){
let sum = 0
arr.forEach(function(element){
sum += element
})
return sum
}
This code defines a function called sumArray that takes one parameter, the array we want to calculate the sum of. Inside the function we set a variable, sum, to 0. Then, we loop over the elements in the array using the forEach method. For each element, we add its value to the sum variable. After looping over every element in the array, we return the sum, which is the total of all elements added together.