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:

  • for repeats a block with a built-in counter or step.
  • while repeats a block while a condition is true.
  • do...while runs a block once first, then repeats while a condition is true.

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:

  • process arrays and other repeated data efficiently,
  • write cleaner code for counters, retries, and searches,
  • stop repeating work when a condition is met,
  • avoid copy-pasting the same statements many times.

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

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.

JavaScript
for (let i = 0; i < 3; i++) {
  console.log(i);
}
Output✓ Tested · Node 24
0
1
2

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.

JavaScript
let count = 0;

while (count < 3) {
  console.log(count);
  count++;
}
Output✓ Tested · Node 24
0
1
2

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.

JavaScript
let attempts = 0;

do {
  console.log("Trying once");
  attempts++;
} while (attempts < 1);
Output✓ Tested · Node 24
Trying once

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.

JavaScript
for (let day = 1; day <= 5; day++) {
  console.log(`Day ${day}`);
}
Output✓ Tested · Node 24
Day 1
Day 2
Day 3
Day 4
Day 5

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.

JavaScript
let temperature = 18;

while (temperature < 22) {
  console.log(`Warming up: ${temperature}°C`);
  temperature++;
}
Output✓ Tested · Node 24
Warming up: 18°C
Warming up: 19°C
Warming up: 20°C
Warming up: 21°C

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.

JavaScript
let inputIsValid = false;
let tries = 0;

do {
  tries++;
  console.log("Prompting for input");
  inputIsValid = tries >= 2;
} while (!inputIsValid);
Output✓ Tested · Node 24
Prompting for input
Prompting for input

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.

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

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

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

5. Practical Use Cases

  • counting from one number to another, such as pagination or progress steps,
  • processing array items when you want direct index control,
  • retrying an operation until it succeeds or times out,
  • validating user input in a repeated prompt flow,
  • scanning for the first matching item in a list,
  • building simple game logic like turn counters or rounds.

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.

JavaScript
let count = 0;

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

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

JavaScript
let count = 0;

while (count < 3) {
  console.log(count);
  count++;
}
Output✓ Tested · Node 24
0
1
2

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.

JavaScript
let ready = false;

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

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

JavaScript
let ready = false;

do {
  console.log("This runs once");
} while (ready);
Output✓ Tested · Node 24
This runs once

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.

JavaScript
for (let i = 0; i <= 3; i++) {
  console.log(i);
}
Output✓ Tested · Node 24
0
1
2
3

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

JavaScript
for (let i = 0; i < 3; i++) {
  console.log(i);
}
Output✓ Tested · Node 24
0
1
2

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.

JavaScript
// Best for a fixed range
for (let i = 0; i < 5; i++) {
  console.log(i);
}
Output✓ Tested · Node 24
0
1
2
3
4

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.

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

for (let i = 1; i <= 3; i++) {
  printSquare(i);
}
Output✓ Tested · Node 24
1
4
9

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.

JavaScript
let tries = 0;
const maxTries = 3;

while (tries < maxTries) {
  tries++;
  console.log(`Attempt ${tries}`);
}
Output✓ Tested · Node 24
Attempt 1
Attempt 2
Attempt 3

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

8. Limitations and Edge Cases

  • Loops can block the main thread if they do too much work, which can freeze a browser tab or slow a Node.js process.
  • A condition that never becomes false creates an infinite loop and can hang your program.
  • do...while is less common than for and while, so some developers may need a moment to read it correctly.
  • Loop counters can behave unexpectedly if you change them in more than one place inside the same body.
  • Floating-point increments are risky for exact counting because decimal math can produce surprising values.
  • When iterating over arrays, changing the array while looping over it can cause skipped items or repeated items depending on the logic.

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.

JavaScript
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.`);
}
Output✓ Tested · Node 24
Tried 1, not correct yet.
Tried 2, not correct yet.
Tried 3, not correct yet.
Tried 4, not correct yet.
Tried 5, not correct yet.
Tried 6, not correct yet.
Found it in 7 tries.

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

  • for is best when the number of iterations is known or count-based.
  • while is best when the loop should continue only while a condition remains true.
  • do...while always runs the body once before checking the condition.
  • Always update the loop state so the loop can stop.
  • Use break when you need to exit early.
  • Choose the loop that makes the intent clearest, not just the one that works.

11. Practice Exercise

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

  • Start from 10.
  • Stop after printing 1.
  • Use a loop that makes the countdown easy to read.

Expected output:

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

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

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

console.log("Liftoff!");
Output✓ Tested · Node 24
10
9
8
7
6
5
4
3
2
1
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.