# [Solved] – JavaScript – How do you find the sum of an array of numbers ?

How do you find the sum of an array of numbers ?

Asked on October 18, 2018 in

In this method For Each method is used to solve the given sum of the arrays .At this code a total array of each function is used total (arr)
function total(arr)

{
if(!Array.isArray(arr)) return;
let sum=0;
arr.forEach(each =>

{
sum+=each;
});
return sum;
};

and if decision statement is used to check if the array is not equal to the function of Array(arr) it is made to return if it is equal it is made to enter into the loop and at initial it is set to 0 and for each values at array the sum made to calculate and stored at the sum when the values made to be equal to zero the sum returns.

In Lisp, this’d be exactly the job for `reduce`. You’d see this kind of code:

``(reduce #'+ '(1 2 3)) ; 6``

Fortunately, in JavaScript, we also have `reduce`! Unfortunately, `+` is an operator, not a function. But we can make it pretty! Here, look:

``````var sum = [1, 2, 3].reduce(add, 0);

return a + b;
}

console.log(sum); // 6``````

Isn’t that pretty? 🙂

Even better! If you’re using ECMAScript 2015 (aka ECMAScript 6), it can be this pretty:

``````var sum = [1, 2, 3].reduce((a, b) => a + b, 0);
console.log(sum); // 6``````