Skip to content
Aabha AI Academy
Skip to reading

JavaScript

Exercise 03: Trace rules and repetition

Use a copy of examples/03.

A. Boundary predictions

For remaining values -1, 0 and 1, write the label each branch should choose. Why is checking zero before positive counts important?

B. Repair

First predict what happens to the final outside-loop console.log if let total = 0 is moved inside the for...of block. Run it and identify the ReferenceError caused by scope. To observe the reset separately, temporarily move the total log inside the loop after the addition: what does it print for [3, 0, 5]? Restore the declaration and final log outside the loop, then trace the correctly accumulated total.

C. Transfer

Without copying the supplied loop, count how many values in [3, 0, 5, 0] are greater than zero. Your result should be 2. Add another positive value and confirm your code adapts without an extra repeated if statement.

Evidence

An iteration trace with the accumulator after each step. Include one empty-array trial; its count should be zero.

Return to lesson · Explained answer

Download this source file