Summing the elements of an array is one of the most common things you'll do with arrays in real code — totaling a cart, averaging scores, aggregating stats. There are two idiomatic ways to do it in JavaScript: a plain for loop, and the array method reduce().

Sum of Array Elements Using a for Loop

const numbers = [12, 45, 7, 23, 9];

let sum = 0;
for (let i = 0; i < numbers.length; i++) {
  sum += numbers[i];
}

console.log("Sum:", sum);

Output:

Sum: 96

This is the most explicit version: start a running total at 0, then loop through the array by index, adding each element to the total as you go.


Sum of Array Elements Using reduce()

reduce() is a built-in array method designed exactly for this kind of "combine everything into one value" problem. It takes a callback function (accumulator, current value) and an initial value for the accumulator, and runs the callback once per element.

const numbers = [12, 45, 7, 23, 9];

const sum = numbers.reduce((total, current) => total + current, 0);

console.log("Sum:", sum);

Output:

Sum: 96

Here, total starts at the initial value 0, and on every call reduce() passes in the running total plus the next array element; whatever the callback returns becomes the new total for the next call. By the time it reaches the last element, total holds the full sum. The same pattern — swapping out the + for other logic — is how you'd compute a product, a maximum, or build up an object from an array.