Course outline · 0% complete

0/29 lessons0%

Course overview →

Array iteration patterns

lesson 4-3 · ~10 min · 12/29

The patterns you will use forever

Most array work reduces to a handful of loop shapes you already met in Python. Here they are in JavaScript, using the for...of loop from lesson 3-3.

Sum (Python's sum(xs) has no built-in here):

let total = 0;
for (const s of scores) {
  total = total + s;
}

Biggest so far:

let best = scores[0];
for (const s of scores) {
  if (s > best) best = s;
}

Count matches: start a counter at 0 and add 1 inside an if.

When the body is a single statement, the braces may be dropped, as in if (s > best) best = s;. In unit 7 you will replace several of these hand-written loops with one-liners like reduce, but the loop versions must feel easy first.

Total, average, and maximum in one pass each

Two of the three patterns applied to the same array. The sum loop feeds the average, which is just the total divided by the length, and the maximum loop runs separately with its own starting guess.

const scores = [80, 95, 62, 74];

let total = 0;
for (const s of scores) {
  total = total + s;
}
console.log(total);
console.log(total / scores.length);

let best = scores[0];
for (const s of scores) {
  if (s > best) best = s;
}
console.log(best);

Output

311
77.75
95

The average prints as 77.75 rather than 77, because JavaScript's single number type never truncates a division. Getting a whole number would take an explicit Math.round(...) or Math.floor(...) around it.

The maximum loop starts with let best = scores[0], seeding the guess with a real item rather than with 0. That choice matters as soon as the data can be negative, which is why the same shape works for temperatures below zero.

Counting the scores that pass

Counting is the sum pattern with an if wrapped around the update. The counter starts at zero and only advances for items that satisfy the test, so items that fail are visited and then ignored.

const scores = [80, 95, 62, 74];

let passing = 0;
for (const s of scores) {
  if (s >= 70) {
    passing = passing + 1;
  }
}
console.log(passing);

Output

3

Three of the four scores clear the bar, since only 62 falls short. Two details generalize well beyond this example. let passing = 0; must sit before the loop, because a counter declared inside the body would be recreated on every lap and never accumulate anything. And the update line has three equivalent spellings, passing = passing + 1, passing += 1, and passing++, with the last two being what you will usually see in real code.

Finding the lowest value

Searching for a minimum is the biggest-so-far pattern with the comparison flipped. Start by assuming the first item is the answer, then replace that guess whenever something smaller turns up.

const temps = [18, 4, 11, -2, 9];
let lowest = temps[0];
for (const t of temps) {
  if (t < lowest) lowest = t;
}
console.log(lowest);

Output

-2

Starting from temps[0] rather than from 0 is what makes this correct for negative numbers. A guess of 0 would never be beaten by -2 if the comparison ran the other way, and worse, it would report 0 as the lowest temperature for an array that contains no zero at all. Seeding the guess with a real item from the array avoids inventing a value that was never in the data.

The single-statement body is written without braces, if (t < lowest) lowest = t;, which is legal and common for short updates like this one. Adding a second statement to that branch would require the braces back.

Start with 3 items. push(4) makes it [1, 2, 3, 4] (length 4). The first pop removes 4, the second pop removes 3, leaving [1, 2] with length 2.

Why it works out that way

  • push(4) grows the array to [1, 2, 3, 4].
  • Each pop removes exactly one item from the end.