Curriculum

Curriculum

Loop Over an Array and Count Matches in JavaScript

Scenario

Run the exact same countOpenRooms fixtures in JavaScript.

Selected choicePick a choice below
Result—
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.

Reveal the explanation
  1. countOpenRooms([])

    0 — identical to Python.

  2. countOpenRooms([1])

    1 — identical to Python.

  3. 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.

Review first
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

Which JavaScript loop reads the element values of an array directly?
Show the answer and reasoning

Correct answer for (const seats of seatCounts)

for..of yields element values, whereas for..in yields string property names.