JavaScript conditions and array loops

Filter values with strict comparisons and accumulate a total.

JavaScript
const values = [-2, 0, 3, 5];
let total = 0;
for (const value of values) {
  if (value > 0) total += value;
}
console.log(total);
if (total !== 8) throw new Error("Unexpected total");
Output
8

Explanation

for...of visits array values. let allows the accumulator binding to change, while const keeps the array binding fixed.

A const array can still have mutable elements; const prevents rebinding, not deep mutation. This example does not modify the input array.

Explore the dry run
Guided walkthroughReady
1const values = [-2, 0, 3, 5];
2let total = 0;
3for (const value of values) {
4 if (value > 0) total += value;
5}
6console.log(total);
7if (total !== 8) throw new Error("Unexpected total");

Follow the example

Start to inspect the source, values, and output. These prepared steps explain the published sample; grouped loop steps describe multiple iterations.

View the complete dry-run table
Prepared trace of the published program. Some rows group repeated iterations.
Step / lineWhat happensState after stepOutput so far
Create four numeric values.values = [-2, 0, 3, 5]
—
Initialize the accumulator.total = 0
—
Skip -2 and 0, then add 3.total = 3
—
Add 5.total = 8
—
Print the result.total = 8
8

Cost and common mistakes

O(n) time and O(1) auxiliary space.

  • for...in enumerates property keys, not array values.
  • Number arithmetic cannot exactly represent every large integer; validate ranges when needed.

Try it yourself

Change the program to count positive values rather than sum them.

Reveal answer and reasoning

Increment total by 1 for every positive value; the result is 2.

Further reading