# How to calculate the sum of array elements?

• 0
We need to write a function that takes an array of numbers and returns their sum.

Here's my bad code:
``````const arr = [20, 40, 77, 53];
const sum = 0;
function count() {
for (i = 0; i < arr.length; i++) {
sum += arr[i];

}
}
count()``````
JavaScript Felicity Thomas, Nov 22, 2019

• 4 Answers
• 0
Strange, so many answers and not a single redux ...

``const count = (arr) => arr.reduce((acc, num) => acc + num, 0);``

And for some reason, nobody was embarrassed that the author assigns a new value to the constant.
Mason Page

• 0
Also as an option:

``````const arr = [20, 40, 77, 53];

function count(arr) {
let sum = 0;
arr.forEach(function(item){
sum += item
})
return sum;
}
count(arr);``````
Anonymous

• 0
1.return sum - skipped)

2.and instead of const you need let (hint WbICHA )
Anonymous

• 0
``````const arr = [20, 40, 77, 53];
const sum = 0;
function count() {
for (i = 0; i < arr.length; i++) {
sum += arr[i];
}
return sum;
}
console.log(count());``````
Anonymous

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!