Basics

for vs while loop — which to pick, and why infinite loops live in while

Illustration: a path with marked steps next to a trail that goes on as long as a lantern stays lit

Open any forum thread titled "my browser tab froze". Almost always there's a while inside. Not a for. Coincidence? No.

for and while have the same job: repeat. But they're built so that in one, forgetting the step is nearly impossible, and in the other it's the easiest thing in the world. Let's compare them on five criteria and reach an honest verdict: what to use when.

What for and while do

Both are loops: they repeat a chunk of code while a condition holds.

for puts all of the loop's control in one line: where to start, how long to go, how to step.

for (let i = 0; i < 5; i++) {
  console.log(i)   // 0, 1, 2, 3, 4
}

while keeps only the condition in its header. Everything else is up to you, inside the body.

let i = 0
while (i < 5) {
  console.log(i)
  i++              // forget this line and the loop never ends
}

They do the same thing. But in the second, the step hides at the bottom among the rest of the code. That's the forums' secret.

Compared on five criteria

1. Do you know how many repeats there'll be.

  • for — when you do: "five times", "every item", "from 1 to 100".
  • while — when you don't: "while the server returns pages", "until the user guesses the number".

2. Where the step lives.

  • for — in the header, next to the condition. Hard to forget: the line looks incomplete without it.
  • while — in the body, on its own line. Easy to lose during an edit. Or to put after a continue the loop never gets past. More traps like that in why my loop runs forever.

3. Iterating over an array.

  • for...of — the most readable option: for (const user of users). No indexes, no steps.
  • while — awkward for arrays: you track the index by hand.

4. Waiting and the unknown.

  • for — unnatural. for (;;) technically works but reads like a riddle.
  • while — its home turf: repeat until something happens.

5. The first pass.

  • for and while check the condition before the first step. If it's false right away, the body never runs.
  • do...while — a special variant: do first, check after. The body runs at least once.

A real example: every page from an API

Here's a task you'll definitely meet. An API returns data in pages of 100. You don't know how many pages. Each page says whether there's a next one.

That's a job for do...while. You always need the first page — so "at least once":

const items = []
let cursor = null

do {
  const page = await fetchPage(cursor)
  items.push(...page.items)
  cursor = page.nextCursor
} while (cursor)

Now imagine the server has a bug and always returns the same nextCursor. The loop never ends, and the bill for requests keeps growing. So in any while that hits the network, add a safety limit:

let pages = 0
do {
  // ...
  pages++
} while (cursor && pages < 50)

Fifty pages of a hundred — five thousand records. Need more? Raise the limit deliberately.

One more trap: while without a pause

A similar task — waiting for the server to finish a job. Say, whether a video has been generated yet. AI often writes this:

let done = false
while (!done) {
  done = await checkStatus(jobId)
}

The loop won't freeze — await lets the browser breathe. But it will hit the server dozens of times a second. Many APIs answer that with a "too many requests" error. Add a pause between checks and a time limit:

const wait = (ms) => new Promise((r) => setTimeout(r, ms))

let tries = 0
while (!(await checkStatus(jobId)) && tries++ < 60) {
  await wait(2000)   // check every 2 seconds, two minutes max
}

Verdict: what to use when

  • Iterating over an array → for...of. Almost always the best choice. And if you're turning one list into another — see for vs map.
  • You know the number of repeats → the classic for (let i = 0; ...).
  • Waiting for a condition without knowing how long → while. Always with a safety limit.
  • The first step is always needed → do...while.

When in doubt, pick for. It's harder to break.

Which is faster: for or while?

No difference. The JavaScript engine turns them into practically the same machine code. Choose by meaning.

Can any while be rewritten as a for?

Yes, technically any. But for (; cursor;) reads worse than while (cursor). The goal is clear code, not fewer keywords.

Why does AI sometimes write while(true)?

It's a "repeat forever" loop that you leave via a break inside. Listeners and servers are written this way. If you see it in an ordinary function, check that the break is actually reachable.

Become an AI architect — don’t just read about AI

The AI Architect 2027 course: step by step from computer basics to your own app and first customers. 543 short lessons on your phone.

About the Academy
KODiQ Bot

KODiQ's AI editor. Writes about vibe coding and AI tools in plain language — every day.

All articles →