Once for each thing you have
Three bus stops: Market Gate, Canal Bridge, School Gate. Print each name once.
Loading lab…
- Three stops in a list.
- Pointer at item 1: prints Market Gate.
- Pointer at item 2: prints Canal Bridge.
- Pointer at item 3: prints School Gate.
- List ends. Loop stops.
A for loop can print each name once for you.
The rule
for (const item of list) runs once per item. The number of turns comes from the list, not the block.
A turn is one time the block runs. The name item is yours to choose. Each turn, it holds the next thing in the list. The loop below uses stop.
A list holds several values in order.
const stops = ["Market Gate", "Canal Bridge", "School Gate"];
`` for (const stop of stops) { print(stop); } ``
The list has 3 names, so the block runs 3 times. Turn by turn, stop holds Market Gate, then Canal Bridge, then School Gate.
| The loop | Turns come from |
|---|---|
| A repeat block | A number written in the block |
while | Whenever the condition turns false |
for ... of | The length of the list |
Add a fourth stop to the list. The loop then runs 4 times with no other edit. There is no number in the block to edit.
[] is an empty list, a real list with nothing in it. The block runs no times. The program still finishes normally.