Loop Over an Array and Count Matches in JavaScript
Scenario
Run the exact same countOpenRooms fixtures in JavaScript.
export function countOpenRooms(seatCounts) {
let openRooms = 0;
for (const seats of seatCounts) {
if (seats > 0) openRooms += 1;
}
return openRooms;
}
// assert.equal(countOpenRooms([]), 0);
// assert.equal(countOpenRooms([1]), 1);
// assert.equal(countOpenRooms([0, 2, 0, 1]), 2);Try it yourself
Compare each case and confirm JavaScript matches Python on every input.
| Case | Result |
|---|---|
| countOpenRooms([]) | Select a choice above to see what happens. |
| countOpenRooms([1]) | Select a choice above to see what happens. |
| for (const seats of seatCounts) vs for (const k in seatCounts) | Select a choice above to see what happens. |
Reveal the explanation
- countOpenRooms([])
0 — identical to Python.
- countOpenRooms([1])
1 — identical to Python.
- for (const seats of seatCounts) vs for (const k in seatCounts)
Use for..of for element values; for..in returns string indices "0", "1", "2".
Use let for the counter that changes and const for the per-pass loop item, and prefer for..of when reading array elements.
Download shared test cases
Your turn
Implement countPassing(scores) in JavaScript with for..of and verify [], [60], and [59, 60, 85].
Common mistake Declaring const openRooms = 0 and then trying to do openRooms += 1, or using for..in instead of for..of.
Check your work
let passed = 0; for (const s of scores) { if (s >= 60) passed += 1; } return passed.
Quick check
This browser could not save your progress. Changes last until you leave the page.