Loops, and where your data lives

INPUT · Slides

Putting the chapter together

01 / 03

You have a full set of tools now

Let us lay out what you picked up in this chapter.

  • repetition (while / for) … the same work, over and over
  • arrays ([ ] / [number] / .length) … things of the same kind held in a row
  • objects ({ } / .name) … the details of one thing held together
  • checking for undefined … stepping around a missing value

Add the variables and branching from the last chapter, and from here it is practice at using them together.

02 / 03

The order you build it in

A problem that looks complicated is nothing to fear once you split it into steps.

  • make the data … decide the shape, array or object
  • run over it … take one entry at a time with for
  • pick … let only the matching ones through with if
  • pile up … keep the total, the count, the maximum in a variable outside
  • show it … display at the end

Rather than writing the lot in one go, the knack is to get one step working and check it.

const scores = [55, 78, 92];let count = 0;for (let i = 0; i < scores.length; i++) {  if (scores[i] >= 70) {    count++;  }}console.log(count);

Result

2

03 / 03

When you get stuck, take it apart

When it will not work, showing the values along the way is the fastest thing you can do.

Add a temporary console.log(i) or console.log(list[i]) and see whether what is in there is what you imagined. An error is fine; you just fix it.

Right then, ten questions.