Overview
Walk through an array with for…of and keep a running count in an accumulator variable.
- for (const x of arr) visits each value
- An accumulator declared with let before the loop
- for…in gives positions, not values
Short Course
for...of visits each value of an array. Keep a total in a let
variable declared before the loop. The trap: for...in gives the positions
("0", "1"…), not the values.
const prices = [5, 12, 3];
let total = 0;
for (const price of prices) {
total += price;
}
total; // 20
Task
Write countPositive(nums) that returns how many numbers are greater than 0,
e.g. countPositive([3, -1, 0, 5]) returns 2.
Test Suites
Pending
Next
Output