A list the program builds itself
Show on a big screenThe kitchen register lists the plates each class needs. It has six rows, one per class. The program reads it row by row and builds a list.
Loading lab…
let meals = []; — the list starts empty.let meals = [];— the list starts empty.- Push 6A's count. One entry.
- Push 6B's count. Two entries.
- Push 7A's count. Three entries.
- Push 7B's count. Four entries.
- Push 8A's count. Five entries.
- Push 8B's count. Six entries.
The rule
.push() adds one value to the end of a list. So a program can build a list while it runs. Where the empty list is made decides what ends up in it.
`` let meals = []; for (const name of register) { const count = platesFor(name); meals.push(count); } ``
register holds the six class names. platesFor(name) looks up one class's plate count. The for loop repeats its lines once for each name.
Run it and meals holds six counts, in register order.
The line let meals = []; must run once, before the loop. If it sits inside the loop, it runs once per class. Every push then goes into a brand-new list. So the list ends with just one count.
Try the lab to finish this lesson.