CodingNeed.

3 · Work with collections · 10 MIN

Repeat with a loop

A loop applies an operation to each item.

for...of visits each array value in order. An accumulator begins with a starting value and changes on each visit. For a sum, the starting value is zero. With n numbers this takes O(n) time and O(1) extra space.

Count the coins in a jar by adding each coin to a running total.

Read the example

let total = 0;
for (const n of [2, 3, 4]) {
  total = total + n;
}
console.log(total);
Check the expected output
9

Your challenge

Return the sum of all numbers in input. An empty list sums to zero.

Common trap

Resetting total inside the loop loses earlier additions.

Next lesson: Select matching items