JavaScript AcademyProfessional Engineering
Level 1 · FoundationsModule 4: Repetition and Problem-SolvingLesson 17 of 150About 40 minutes

Lesson 17: While and do-while loops

01Opening question

A savings app asks: how many months until I reach $1,000? You do not know the number of repetitions in advance. How can a loop handle that?

Keep the question in mind. By the end of the lesson you will be able to answer it, and prove it with working code.

02Start with working code

The loop keeps going while the condition is true. Something in the body must eventually make it false.

let balance = 100;
let months = 0;
while (balance < 150) {
  balance += 20;
  months++;
}
console.log(months, balance);

03Objective and prerequisites

Learning objective: Use while loops when the number of iterations is unknown, use do...while when the body must run at least once, and prevent infinite loops.

You need: Lesson 16: For loops

Skills practised: Loops, while and do...while loops.

04Explanation

A while loop has only a condition: while (condition) { ... }. It checks the condition, runs the body if it is true, and checks again.

Use while when you do not know how many times to repeat, only when to stop: until a balance reaches a goal, until a user types "quit", until there is no more data.

The body must change something the condition depends on. If nothing changes, the condition stays true forever: an infinite loop. The academy stops runaway loops for you; a real browser tab would freeze.

do { ... } while (condition); runs the body first and checks afterwards, so the body always runs at least once. It suits menus and "ask again" prompts.

05Definitions

while loop
A loop that repeats while its condition is true, checking before each pass.
do...while loop
A loop that runs its body once, then repeats while its condition is true.
Infinite loop
A loop whose condition never becomes false.
Sentinel value
A special value, such as "quit" or -1, that signals a loop to stop.
Loop guard
An extra condition, such as a maximum number of attempts, that stops a loop safely.

Open the full glossary

06Visual learning object

While-loop condition tracker. Step through a while loop and watch the condition being checked before every pass.

Loading the interactive object…

Open the full While-loop visualizer page with its guided experiment.

07Examples

ex-017-01Until a goal is reached Browser-executable JavaScript

The number of months is the result, not the input.

let balance = 400;
let months = 0;
while (balance < 1000) {
  balance += 150;
  months++;
}
console.log(`Goal reached in ${months} months with $${balance}`);
Sample input
None
Expected output
Goal reached in 4 months with $1000
Common mistake
Forgetting months++ and always printing 0.
Try this
Change the deposit to 120 and predict the months.
Source
examples/ex-017-01-savings-goal.js (repository pending publication)

ex-017-02Halving until small Browser-executable JavaScript

Each pass changes the value the condition checks.

let size = 64;
let steps = 0;
while (size > 1) {
  size = size / 2;
  steps++;
}
console.log(steps);
Sample input
None
Expected output
6
Common mistake
Writing size / 2 without assigning it, so size never changes.
Try this
Start at 1000 and use Math.floor when halving.
Source
examples/ex-017-02-halving.js (repository pending publication)

ex-017-03do...while runs at least once Browser-executable JavaScript

Even when the condition is false at the start, the body runs one time.

let attempts = 0;
do {
  attempts++;
  console.log("Showing menu, attempt", attempts);
} while (attempts < 0);
console.log("attempts:", attempts);
Sample input
None
Expected output
Showing menu, attempt 1 attempts: 1
Common mistake
Expecting do...while to skip the body when the condition is false.
Try this
Change the condition to attempts < 3 and predict the output.
Source
examples/ex-017-03-do-while-menu.js (repository pending publication)

ex-017-04Stopping at a sentinel Browser-executable JavaScript

The loop reads values until it finds the stop marker.

const inputs = ["add", "add", "quit", "add"];
let i = 0;
let added = 0;
while (inputs[i] !== "quit") {
  added++;
  i++;
}
console.log("Commands before quit:", added);
Sample input
None
Expected output
Commands before quit: 2
Common mistake
Forgetting i++ so the loop reads the same input forever.
Try this
Add a guard so the loop also stops at the end of the array.
Source
examples/ex-017-04-sentinel.js (repository pending publication)

08Guided exercises

Three exercises: explore and modify, complete the implementation, then build independently. Tests check behaviour, so any correct solution passes.

Make the countdown stop

Change the state a while condition depends on.

let seconds = 3;
while (seconds > 0) {
  console.log(seconds);
  seconds - 1;
}
console.log("Go!");

Doubling followers

Count iterations until a condition is met.

let followers = 50;
let days = 0;
// TODO: double followers each day until it is at least 1000
console.log(`${days} days, ${followers} followers`);

PIN attempts with a guard

Combine a sentinel condition with a maximum attempt guard.

const correctPin = "2580";
const typed = ["1111", "0000", "2580", "9999"];
const MAX_ATTEMPTS = 3;

09Prediction

Commit to an answer first, then run the real code to compare.

let n = 10;
do {
  n += 5;
} while (n < 10);
console.log(n);

What is printed?

10Debugging investigation

The savings plan stops one month early

The app says the $500 goal is reached, but the balance it prints is below $500.

const GOAL = 500;
let balance = 0;
let month = 0;
while (balance < GOAL - 100) {
  balance += 100;
  month++;
}
console.log(`Month ${month}: $${balance}`);

More cases in the Debugging Detective Laboratory

11Practical scenario

Retrying a download

An app retries a failed download until it succeeds, but never more than three times. A while loop with a success flag and an attempt guard expresses both rules.

const results = [false, false, true];
let attempt = 0;
let ok = false;
while (!ok && attempt < 3) {
  ok = results[attempt];
  attempt++;
}
console.log(ok, attempt);

12Knowledge check

1. What is printed?

let n = 0;
while (n < 3) n++;
console.log(n);
  • 3
  • 4
  • 0
  • It never ends

2. When does do...while check its condition?

  • Before the first pass
  • After each pass
  • Never
  • Only once

3. Why does this never stop?

let total = 0;
while (total < 100) {
  total + 10;
}
  • while needs a counter
  • total is never changed
  • 100 is too large
  • while cannot use <

4. Which loop fits "repeat until the user types quit"?

  • for with a fixed count
  • while
  • if
  • switch

5. What is printed?

let x = 0;
do { x++; } while (false);
console.log(x);
  • 0
  • 1
  • Nothing
  • An error

6. A loop reads server data. What makes it safer?

  • No condition
  • A maximum attempts guard
  • Using == instead of ===
  • Removing the update

13Solutions and tests

Each exercise's solution appears in the exercise once you have run its tests. Solutions are one possible answer: the tests accept any implementation with the same behaviour.

Automated acceptance tests for this lesson

These are the same checks the exercises run. They are visible on purpose: client-side tests help you learn and are not secret.

  • Make the countdown stop: Counts down then Go!; Uses while
  • Doubling followers: Prints the result; days is 5; Uses while
  • PIN attempts with a guard: Unlocks on attempt 3; unlocked is true; Uses the guard
  • ex-017-01: output matches the documented expected output
  • ex-017-02: output matches the documented expected output
  • ex-017-03: output matches the documented expected output
  • ex-017-04: output matches the documented expected output

Download the whole lesson folder (examples, exercises, solutions, tests) as ZIP

14Source files

The lesson lives in the companion repository at curriculum/level-01-foundations/module-04-repetition-and-problem-solving/lesson-017-while-and-do-while-loops/. Every example on this page is generated from those files.

The GitHub repository (https://github.com/lsvekis/JavaScript-Professional-Academy) has not been published yet, so these links will work once it is. Until then, use the ZIP download above.

15Summary and next steps

  • while repeats while a condition is true, checking first.
  • do...while runs at least once.
  • The body must change what the condition depends on.
  • Add a maximum-attempts guard when data controls the loop.

16AI learning prompts

Copy a prompt into the AI assistant of your choice. Then verify what it says by running code here. No AI service is connected to this page.

Concept explanation while and do...while
Context: I know for loops.
Task: Explain when to use while and do...while instead, with three real situations each.
Constraints: Beginner level.
Expected behaviour: I can choose the right loop.
Testing: Ask me to pick a loop for five situations.
Code prediction Loop condition drill
Context: I know while loops.
Task: Give me six while and do...while loops and ask what each prints.
Constraints: Include one infinite loop.
Expected behaviour: Each has one answer.
Testing: Explain the state change each time.
Debugging Frozen program
Context: My while loop never ends.
Task: Ask me questions that lead me to the variable that never changes.
Constraints: No direct answer.
Expected behaviour: I fix it myself.
Testing: Suggest a loop guard.
Exercise generation Unknown repetitions
Context: I finished the doubling followers exercise.
Task: Create three exercises where the number of repetitions must be calculated.
Constraints: Fictional data, exact output.
Expected behaviour: Use money, time and growth.
Testing: Include expected output.
Code review Loop safety
Context: My loop retries until a request succeeds.
Task: Review it for infinite-loop risks.
Constraints: Suggest guards and clear names.
Expected behaviour: The loop always terminates.
Testing: List the changes.