JavaScript for, while, and do...while Loops Explained

JavaScript loops let you repeat code until a condition changes. This article explains the three core loop statements—for, while, and do...while—so you can choose the right one, write correct iteration logic, and avoid common bugs like infinite loops and off-by-one errors.

Quick answer: Use for when you know how many times you want to repeat, while when you want to keep going until a condition changes, and do...while when the loop must run at least once.

Difficulty: Beginner

You'll understand this better if you know: basic variables, comparison operators, and how to read a simple block of JavaScript statements.

1. What Are for, while, and do...while Loops?

Loops are control structures that run the same block of code multiple times. In JavaScript, these three statements cover the most common iteration patterns:

All three are useful when you need to process lists, count numbers, wait for a condition, or keep asking for input until it is valid.

2. Why These Loops Matter

Without loops, you would have to write the same code again and again. That becomes hard to maintain, easy to break, and impossible to scale when the number of repetitions changes.

Loops matter because they let you:

These loop statements are also the foundation for many higher-level JavaScript patterns, even when you later use methods like map or forEach.

3. Basic Syntax or Core Idea

The for loop

The for loop bundles initialization, condition checking, and update logic into one line. It is often the clearest choice for counted repetition.

for (let i = 0; i < 3; i++) {
  console.log(i);
}

This example starts at 0, checks whether i is less than 3, prints the value, and then increases i by 1 after each iteration.

The while loop

The while loop checks a condition before each repetition. If the condition is false at the start, the body never runs.

let count = 0;

while (count < 3) {
  console.log(count);
  count++;
}

Here, the loop continues until count reaches 3.

The do...while loop

The do...while loop checks the condition after the body runs. That guarantees at least one execution.

let attempts = 0;

do {
  console.log("Trying once");
  attempts++;
} while (attempts < 1);

This pattern is useful when you must run code once before checking whether it should continue.

4. Step-by-Step Examples

Example 1: Counting upward with for

A for loop is ideal when the number of iterations is known or can be expressed as a range.

for (let day = 1; day <= 5; day++) {
  console.log(`Day ${day}`);
}

This prints five lines, one for each day. The counter changes in a predictable way, which makes for easy to read.

Example 2: Repeating until a value changes with while

A while loop is good when the number of repetitions is unknown.

let temperature = 18;

while (temperature < 22) {
  console.log(`Warming up: ${temperature}°C`);
  temperature++;
}

The loop stops only when the condition becomes false. This is common for searches, retries, and waiting for state changes.

Example 3: Running at least once with do...while

Use do...while when the first run must happen before the decision is made.

let inputIsValid = false;
let tries = 0;

do {
  tries++;
  console.log("Prompting for input");
  inputIsValid = tries >= 2;
} while (!inputIsValid);

This shows the important behavior: the body runs once even though the condition starts out false.

Example 4: Using break to stop early

Sometimes a loop starts with a broad condition, but you want to stop as soon as you find what you need.

const numbers = [4, 7, 9, 12];

for (let i = 0; i < numbers.length; i++) {
  if (numbers[i] === 9) {
    console.log("Found 9");
    break;
  }
}

break exits the loop immediately, which is useful in search-style tasks.

5. Practical Use Cases

When your loop body needs to know the current index, for is often the clearest choice. When the loop depends on state changing over time, while usually reads better.

6. Common Mistakes

Mistake 1: Forgetting to update the loop variable

Each loop needs a way to move toward its stopping condition. If that update never happens, the loop may never end.

Problem: The condition stays true forever because count never changes, so the loop becomes infinite.

let count = 0;

while (count < 3) {
  console.log(count);
}

Fix: Update the variable inside the loop so the condition can eventually become false.

let count = 0;

while (count < 3) {
  console.log(count);
  count++;
}

The corrected version works because the loop moves toward termination on every pass.

Mistake 2: Using the wrong loop when the first run matters

A while loop checks before entering the body. If the condition is already false, the body does not run at all.

Problem: This code never runs because the starting condition is false, even though the developer expected one execution.

let ready = false;

while (ready) {
  console.log("This should run once");
}

Fix: Use do...while when the body must execute at least once.

let ready = false;

do {
  console.log("This runs once");
} while (ready);

The corrected version works because do...while always executes the body before checking the condition.

Mistake 3: Off-by-one errors in loop conditions

One of the most common loop bugs is using the wrong comparison operator, which causes one too many or one too few iterations.

Problem: The loop runs four times instead of three because <= includes the end value.

for (let i = 0; i <= 3; i++) {
  console.log(i);
}

Fix: Use < when you want a count of exactly three iterations starting at zero.

for (let i = 0; i < 3; i++) {
  console.log(i);
}

The corrected version works because the loop stops before the counter reaches 3.

7. Best Practices

Practice 1: Pick the loop that matches the problem

Use for for counted iteration, while for condition-driven repetition, and do...while for at-least-once behavior. Matching the loop to the problem makes the code easier to read.

// Best for a fixed range
for (let i = 0; i < 5; i++) {
  console.log(i);
}

This keeps your intent obvious to future readers.

Practice 2: Keep the loop body small and focused

Large loop bodies are harder to debug because a single repetition may do too many things. Move repeated work into a function when it helps readability.

function printSquare(n) {
  console.log(n * n);
}

for (let i = 1; i <= 3; i++) {
  printSquare(i);
}

This version is easier to extend and test than putting all logic inline.

Practice 3: Use strict stopping conditions

Write loop conditions that are as specific as possible. Vague conditions increase the chance of accidental infinite loops or extra iterations.

let tries = 0;
const maxTries = 3;

while (tries < maxTries) {
  tries++;
  console.log(`Attempt ${tries}`);
}

This makes the end point easier to reason about and change later.

8. Limitations and Edge Cases

Warning: A loop that never stops can freeze the browser or consume CPU endlessly, so always make sure your exit condition is reachable.

9. Practical Mini Project

In this mini project, we will build a simple number guessing loop that keeps asking until the secret number is found. This shows a realistic use of while plus break.

const secretNumber = 7;
let guess = 0;
let attempts = 0;

while (true) {
  attempts++;
  guess = attempts;

  if (guess === secretNumber) {
    console.log(`Found it in ${attempts} tries.`);
    break;
  }

  console.log(`Tried ${guess}, not correct yet.`);
}

This example uses an intentional endless loop with a break statement. That pattern is useful when the stopping point depends on a condition discovered during the loop rather than before it starts.

10. Key Points

11. Practice Exercise

Write a loop that prints numbers from 10 down to 1, then prints Liftoff!.

Expected output:

10
9
8
7
6
5
4
3
2
1
Liftoff!

Hint: A for loop with a decreasing counter is a natural fit.

Solution:

for (let i = 10; i >= 1; i--) {
  console.log(i);
}

console.log("Liftoff!");

This solution uses a downward counter, which is one of the simplest and most readable loop patterns in JavaScript.

12. Final Summary

JavaScript’s for, while, and do...while loops all repeat code, but each one fits a different shape of problem. for is the best match for counted repetition, while fits condition-driven repetition, and do...while is the right choice when the body must run before the condition is checked.

The most important habit is to make your stopping condition clear and reachable. That prevents infinite loops, off-by-one mistakes, and confusing control flow. Once you can recognize the differences between the three loop types, you can write simpler iteration logic and choose the clearest structure for each task.

As a next step, practice combining these loops with break, continue, and arrays so you can handle more realistic iteration problems confidently.