JavaScript · Course navigation

JavaScript conditions and array loops

Filter values with strict comparisons and accumulate a total.

On this page
Before you start

const, let, and arrays.

  • Filter values with strict comparisons and accumulate a total.
  • Predict the sample output and explain the state changes.
  • Complete the practice task and check the boundary cases.

The concept

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.

Code example

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

Follow the code

Open the walkthrough to inspect the example one step at a time.

Show guided walkthrough
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

Behind the scenes

How JavaScript processes this code

A JavaScript engine parses and runs the source. A function body runs when the function is called. console.log writes to the console.

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