Choosing a Loop

while, for-of, and for-i can all do the same job — the choice is comfort, not capability.

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: Repeating Until Something Changes

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.

for-of: Just Give Me Each Value

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.

for-i: When the Position Itself Matters

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.

Rule of Thumb

  • Repeating until some condition changes, no array involved? Use while.
  • Just need each value in an array, in order? Use for...of.
  • Need the position of each item? Use for-i.