Loops, and where your data lives

INPUT · Slides

Working through an array with a loop

01 / 05

Writing the numbers by hand has a limit

Three items and you can write list[0] list[1] list[2]. Twenty items is twenty lines.

This is where to remember that a variable can go inside [ ]. And that repetition is very good at stepping a variable up by one. Put the two together.

02 / 05

Use the counter as the number

Use the i from your for as the number and you take out a different item every lap.

The trick is starting at 0, because that is where array numbering starts.

const fruits = ["apple", "orange", "peach"];for (let i = 0; i < 3; i++) {  console.log(fruits[i]);}

Result

apple
orange
peach

03 / 05

Why 0 and "less than"

An array of three has numbers 0 1 2, so i only needs to travel from 0 to 2.

Start at i = 0 with the condition i < 3 and you get exactly three laps: 0 1 2. "From 0, up to less than the count" is the watchword for this pairing.

Write i <= 3 and it goes looking for a number 3, so take care.

04 / 05

Piling up a total

Pile up the values you take out and you get the total of the lot.

The piling variable goes outside the repetition, same as ever.

const scores = [80, 95, 60];let total = 0;for (let i = 0; i < 3; i++) {  total += scores[i];}console.log(total);

Result

235

05 / 05

Mixing in a condition

Write an if inside the { } and you can work through it picking as you go.

With arrays, repetition and branching all in hand, what you can do widens out fast. Take it into your body with the practice from here.

const scores = [45, 88, 72];for (let i = 0; i < 3; i++) {  if (scores[i] >= 60) {    console.log(scores[i]);  }}

Result

88
72