You've now met three loops: while, for...of, and for-i. They can all technically do each other's job, so the real skill isn't knowing that — it's recognizing which one fits the shape of the problem in front of you, so you're not fighting the loop to get what you want.
while doesn't know anything about arrays. It just keeps going as long as a condition is true. That makes it the natural fit when you're not walking through a collection at all — you're waiting for a value to cross a threshold, or for something to eventually succeed.
let count = 0;
while (count < 5) {
count = count + 1;
}
// count is now 5
There's no array here, and no fixed number of laps decided in advance. You genuinely don't know how many times this will run until you run it — that's exactly the situation while is built for.
Once you do have a collection and you want to do something with every item in it, for...of says exactly that and nothing more — no counter, no condition to maintain, no array indexing.
const prices = [4.5, 12, 8.25, 30];
let total = 0;
for (const price of prices) {
total = total + price;
}
// total is 54.75
You never touch position here because the task never needed it — you just needed every value, once each, in order. Reaching for a counter in a loop like this would be pure overhead.
Sometimes the value alone isn't enough — you need where it is. for...of doesn't hand you a number to work with, so for-i is the loop built for exactly that:
const fruits = ["apple", "banana", "cherry"];
for (let i = 0; i < fruits.length; i++) {
const positioned = i + ": " + fruits[i];
}
// positioned is "0: apple", then "1: banana", then "2: cherry"
i isn't a workaround here — it's the point. The loop hands you the position on every lap, already counted, instead of making you track it by hand the way you would with for...of.
while. for...of. for-i.