Thuta Learning
JavaScript
BasicProgrammingBeginner

JS While Loop

JavaScriptLesson 1020 min

What you'll walk away with

  • Explain that while checks its condition before every pass and may run zero times
  • Choose while over for when the number of iterations is not known in advance
  • Avoid infinite loops by moving the condition toward false inside the body
  • Use do...while for work that must happen at least once
  • Add a maximum-attempts guard to retry and pagination loops

Explain it simply

Explain it simply

Imagine emptying a bucket of water with a cup. You do not know in advance how many scoops it will take; you only have one rule: keep scooping while there is still water in the bucket. After each scoop you look again, and you stop the moment it is empty.

A while loop follows exactly that rule. while (condition) { ... } runs its body again and again as long as the condition stays true. A for loop suits work with a known count, like "do this ten times", while a while loop suits work that depends on a state, like "keep going until it is done".

Problem → Why → Solution

The problem: a retry loop that never ends

This loop keeps trying to connect to a server until it succeeds. On normal days it works fine, but one night while the server is under maintenance, the whole browser tab freezes and the CPU fan starts roaring. Inside Node.js, the process would stop answering any request at all.

retry.js
let connected = false;

while (!connected) {
  connected = tryConnect(); // server is down: always returns false
}

console.log("Connected!"); // never reached

Why does it never stop?

A while loop stops only when its condition becomes false. Here the only thing that can make it false is the server, and if the server never comes back, the loop spins forever. JavaScript runs this code on a single thread, so the loop blocks everything else on the page. Only a guard, such as a limit on attempts, guarantees the loop will end.

Core concept: condition, progress and guard

while (condition) { body } is like a for loop with only the condition part kept. You write the initialization yourself before the loop, and the update yourself inside the body. The condition is checked before every pass, so if it is false on the very first check, the body never runs. That is not a bug; it means "if there is nothing to do, do nothing".

Every loop has one rule: the body must move the condition one step closer to false. That progress might be incrementing a counter, removing an item from a queue, or taking the next page's cursor. Without progress, the loop never ends. When progress depends on something outside your program, such as a server, a user or a file, add a guard like a maximum number of attempts or pages to the condition: while (!done && attempts < 5).

do { body } while (condition); checks its condition after the body, so the body always runs at least once. It suits work where you try once and then decide whether to repeat, such as showing a menu or asking for input. Do not forget the semicolon after (condition).

break and continue work inside while too. The while (true) { ... if (done) break; } shape is common when the exit point sits in the middle of the body, but keep that break in one easy-to-find place. Network retries also need a pause between attempts, which the async/await lessons cover later.

LoopPick it when
forYou know the count or the index range up front
whileYou repeat until a state changes, and zero passes is acceptable
do...whileThe first pass must always happen before any check
Mental model: check, run, make progress
  1. Check the condition
  2. False means leave the loop
  3. Run the body
  4. Body moves condition toward false

A while loop without progress is an infinite loop; when in doubt, add a guard.

General pattern

javascript
// set up state before the loop
while (condition) {
  // do the work
  // change state so condition can become false
}

do {
  // runs at least once
} while (condition);

while checks first and then runs; do...while runs first and then checks. In both, you set up the state before the loop and change it inside the body.

Example: counting from 0 to 4

This example counts in the simplest way so the three moving parts of a while loop are easy to see. It also prints i after the loop, which shows exactly why the loop stopped.

count.js
let i = 0;

while (i < 5) {
  console.log("The number is " + i);
  i++;
}

console.log("After the loop, i is " + i);

Code breakdown

  1. Line 1let i = 0;

    The initialization lives outside the loop, which is why i is still usable after the loop ends.

  2. Line 3while (i < 5) {

    i < 5 is checked before every pass. Had i started at 10, the body would never run.

  3. Line 5i++;

    This is the progress step. Delete it and i stays at 0, printing "The number is 0" forever.

  4. Line 8console.log("After the loop, i is " + i);

    Shows that i reached 5, where 5 < 5 is false, so the loop stopped. The body ran five times, for 0 through 4.

You should see
The number is 0
The number is 1
The number is 2
The number is 3
The number is 4
After the loop, i is 5

Loops whose length you cannot know in advance

Many APIs return data one page at a time, and each page carries the cursor of the next one. You cannot know how many pages there are, so while fits naturally. The code below fakes the API with an object and reads until no cursor is left. The MAX_PAGES guard stops the loop even if a buggy API keeps returning a cursor forever.

pagination.js
const pages = {
  start: { items: ["a", "b"], next: "p2" },
  p2: { items: ["c", "d"], next: "p3" },
  p3: { items: ["e"], next: null },
};

const MAX_PAGES = 10;
let cursor = "start";
let pageCount = 0;
const collected = [];

while (cursor !== null && pageCount < MAX_PAGES) {
  const page = pages[cursor];
  for (const item of page.items) collected.push(item);
  cursor = page.next; // progress: move to the next page
  pageCount++;        // guard: count every page we read
}

console.log("Read " + pageCount + " pages, " + collected.length + " items");

do...while is for work that must be tried at least once. Here an array fakes what a user types, and the loop keeps asking until it gets a non-blank answer.

ask-name.js
const typed = ["", "   ", "Mya"]; // what the user types, one try at a time
let attempts = 0;
let name;

do {
  name = typed[attempts].trim();
  attempts++;
} while (name === "" && attempts < typed.length);

console.log("Got " + name + " after " + attempts + " attempts");

In real projects

Where while loops show up in real projects

Backend sync jobs pull records page by page from a payment provider or CRM API. Like the pagination loop in the deeper section, they read until no cursor is left and log how many records arrived. In production the maximum-page guard is essential: if an API bug keeps returning the same cursor, a job without a guard can run all night and burn through the whole API quota. Teams also catch failed requests and record which page the job stopped on.

Game loops, queue workers that process jobs one by one while the queue is not empty, and text parsers that read token after token until the end of a file all use while as well. In each case the loop is controlled by "until when" rather than "how many times".

Common mistakes

Common mistakes

1. Forgetting the progress step

Delete the i++ from the example and i < 5 stays true forever. After writing any while loop, point to the exact line in the body that changes the condition. If you cannot find one, you probably have an infinite loop.

2. A continue that skips the progress step

In while (i < 5) { if (i === 2) continue; console.log(i); i++; }, once i reaches 2, continue skips the i++ and jumps back to the condition, so i is stuck at 2 forever. A for loop avoids this because its update lives in the header, but in a while loop the increment must come before any continue.

3. Retrying without a guard

Loops that depend on an outside system, like while (!connected) in the problem section, freeze the program during an outage unless they also check attempts < maxAttempts. When the guard runs out, report a clear error.

Best practices

Best practices

  • Keep the progress step in one spot, at the start or end of the body, not split around continue statements.
  • Store guards such as MAX_PAGES or MAX_ATTEMPTS in named constants instead of bare numbers like 10.
  • After the loop, check and log why it stopped: success, or the guard running out.

Mini challenge

Mini challenge: a retry loop with a guard

Connection attempts are faked with an array of results. Write connectWithRetry() with a while loop that keeps trying until it connects or reaches maxAttempts.

  • results[k] is the outcome of attempt number k + 1 (true means connected)
  • The condition checks both whether we are connected and attempts < maxAttempts
  • Print "Attempt N: connected" or "Attempt N: failed" after every try
  • Return a { connected, attempts } object
retry.js
function connectWithRetry(results, maxAttempts) {
  // TODO: keep track of attempts and whether we are connected

  while (/* TODO: not connected yet AND attempts left */) {
    // TODO: read this attempt's result from results
    // TODO: make progress, then print "Attempt N: connected" or "Attempt N: failed"
  }

  // TODO: return { connected, attempts }
}

console.log(connectWithRetry([false, false, true], 5));
console.log(connectWithRetry([false, false, false, false], 3));

Expected: Attempt 1: failed Attempt 2: failed Attempt 3: connected { connected: true, attempts: 3 } Attempt 1: failed Attempt 2: failed Attempt 3: failed { connected: false, attempts: 3 }

Show hint

Comparing results[attempts] === true safely treats an out-of-range undefined as a failure. Increment attempts before printing so the numbering starts at 1.

Show solution
retry.js
function connectWithRetry(results, maxAttempts) {
  let attempts = 0;
  let connected = false;

  while (!connected && attempts < maxAttempts) {
    connected = results[attempts] === true;
    attempts++;
    console.log("Attempt " + attempts + ": " + (connected ? "connected" : "failed"));
  }

  return { connected, attempts };
}

console.log(connectWithRetry([false, false, true], 5));
console.log(connectWithRetry([false, false, false, false], 3));

Quick quiz 1 / 3

What does let n = 0; do { n++; } while (n < 0); console.log(n); print?

Quick quiz 2 / 3

After let n = 20, steps = 0; while (n > 1) { n = n / 2; steps++; }, what is steps?

Quick quiz 3 / 3

What happens with let i = 0; while (i < 5) { if (i === 2) continue; console.log(i); i++; }?

What to remember

  • while checks before every pass and can run zero times; do...while always runs at least once.
  • Reach for while when the number of passes is not known in advance.
  • The body must always move the condition toward false, and continue must not skip that progress.
  • Give every loop that depends on an outside system a maximum-attempts guard.

MDN — JavaScript Guide — MDN Web Docs

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.