while and for...of
More loop options: while for conditions and for...of for arrays
We already know for — it's ideal when we know the number of repetitions. But there are two other important loops:
- while — repeats while a condition is true (count unknown in advance)
- for...of — iterates over array elements one by one (most convenient for lists)
while — like waiting for a bus
You're at a bus stop and repeating one action: 'While the bus hasn't arrived — wait'. You don't know how many minutes you'll wait — you just wait until the condition becomes false. That's exactly how while works.
countdown-- decrements the counter. Without this the loop would never stop!
Infinite loop — the most common while mistake. If the condition never becomes false — the program will freeze. Always make sure the variable in the condition changes!
for...of — like reading a shopping list
You take a shopping list and read each item in order. for...of does the same with an array: takes each element and executes code. No need to track indices — just 'for each element do this'.
for...of reads as 'for each fruit in fruits'. No indices!
Summary: for — when you know the number of steps. while — when you don't know (waiting for a condition). for...of — when iterating over an array.