Anjan Dutta

Sum of all array items in javascript

Sum of all array items in javascript

Creted On: 27/10/2021

There are two methods we can use to get the sum of all array items in javascript.

Using the for loop

The for loop will iterate through each item and add to an initial value which is 0.

const number_list = [17, 20, 13];
let temp = 0;
for (let i=0; i< number_list.length; i++) {
temp += number_list[i];
}
console.log(temp);
// 50

Using reduce method

We can use the reduce method like below example.

const number_list = [17, 20, 13];
const sum = number_list.reduce((a, b) => {
return a+b;
}
);
console.log(sum);