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
1
const values = [-2, 0, 3, 5];2
let total = 0;3
for (const value of values) {4
if (value > 0) total += value;5
}6
console.log(total);7
if (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
| Step / line | What happens | State after step | Output 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.