Coding

Difference Between For Loop and While Loop (With Examples)

A for loop is built for a known number of passes or a known collection of items: it keeps its setup, test and update in one place. A while loop is built for "keep going until something changes": it holds only a condition, and the body is responsible for eventually making that condition false.

The two are closely related, and anything one can do the other can do. The practical difference is which one makes the code easier to read and harder to get wrong. The examples below use Python and JavaScript, but the idea carries over to C, Java, C# and most other languages. For language-specific syntax, see the JavaScript for loop guide.

For loop vs while loop at a glance

Questionfor loopwhile loop
Typical useCount from A to B, or visit every item in a collectionRepeat until an event happens (input is valid, a file ends, a value converges)
Where the loop control livesIn the loop header (JavaScript, C, Java) or in the iterable (Python)Split between a variable declared earlier, the condition, and an update inside the body
Number of passes known in advanceUsually yesUsually no
Can the body run zero timesYesYes
Easy to forget the update stepNo, it is part of the headerYes, and that causes infinite loops

How a for loop works

In Python, a for statement does not count. It walks an iterable. The language reference says the expression is evaluated once, an iterator is created, each item is assigned to the target in turn, and the loop ends when the iterator is exhausted:

for name in ["ada", "grace", "alan"]:
    print(name)

To count in Python you loop over range(), for example for i in range(5):.

In JavaScript, C, Java and C#, the classic form has three parts in the header. MDN describes them for JavaScript: the initialization runs once before the loop begins, the condition is evaluated before each iteration, and the afterthought runs at the end of each iteration:

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

Because all three parts sit on one line, you can read the whole life of the counter at a glance: it starts at 0, continues while it is below 5, and goes up by 1. MDN also notes that all three header expressions are optional, and that omitting the condition makes it always true, so for (;;) is an infinite loop unless the body uses break.

How a while loop works

A while loop has only a condition. Python's reference says it "repeatedly tests the expression and, if it is true, executes the first suite". MDN says the condition is "evaluated before each pass through the loop":

count = 0
while count < 5:
    print(count)
    count += 1

Here the three jobs a for header does are scattered. The starting value is set on the line above, the test is in the header, and the update is the last line of the body. If you delete count += 1, the condition stays true forever and the program never finishes.

Both references make one more point: the test happens first. Python notes the else suite runs if the expression is false, "which may be the first time it is tested". So a while loop whose condition starts out false runs its body zero times. The same is true of a for loop over an empty list.

When to use a for loop

Use a for loop when you can say in advance what you are looping over:

  • Every item in a list, array, string, dictionary or file. In Python and in JavaScript's for...of, the language handles the stepping, so there is no index to get wrong.
  • A fixed count. Repeat something 10 times, or process indexes 0 to 99.
  • A range of numbers with a regular step. Every second item, or counting down from 10 to 1.

The benefit is that the loop's boundaries are visible in one place, which makes off-by-one mistakes easier to spot. If you are stacking loops inside each other to walk a grid, see nested for loops explained.

When to use a while loop

Use a while loop when the stopping point depends on something that happens while the loop runs, and you cannot count the passes beforehand:

  • Retry until valid. Ask for input again until the user types a valid number.
  • Read until the end. Read lines from a stream or socket until it reports no more data.
  • Converge. Keep refining an estimate until the change drops below a tolerance.
  • Wait on a state. Poll a job until it reports "done" or a timeout passes.

A concrete example is halving a number until it is below 1. You cannot write the count down without doing the work:

value = 100.0
steps = 0
while value >= 1:
    value /= 2
    steps += 1
print(steps)

Example output: 7. The value goes 100, 50, 25, 12.5, 6.25, 3.125, 1.5625, 0.78125, so seven halvings are needed. A for loop could do this only by guessing an upper bound and then breaking out early.

Converting between the two

Any for loop can be written as a while loop by moving the pieces apart. These two JavaScript snippets print the same thing:

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

let j = 0;
while (j < 3) {
  console.log(j);
  j++;
}

The reverse works too: a while loop is a for loop with the initialization and afterthought left empty, as in for (; condition; ). Nobody writes it that way, because the while form says the same thing with less noise. That is the real rule of thumb: if you would leave two of the three header slots empty, use while.

There is one subtle difference. In a JavaScript for loop, continue jumps to the afterthought and then tests the condition. In the hand-written while version above, continue jumps straight to the condition, skipping j++, and the loop can hang. Put the update before the continue, or use the for form.

Shared tools: break, continue and else

Both loops support break to leave immediately and continue to skip to the next pass. Python adds an else clause to both. Per the language reference, the else suite runs when the loop ends normally (the condition went false, or the iterator ran out) and is skipped when the loop exits through break:

for n in [3, 5, 7]:
    if n % 2 == 0:
        print("found an even number")
        break
else:
    print("no even numbers")

Example output: no even numbers.

Common mistakes

  • Forgetting the update in a while loop. If nothing in the body changes what the condition tests, it never ends. Check that every path through the body moves toward the exit.
  • Off-by-one in the condition. i <= 5 runs six times from 0, while i < 5 runs five. Write down the first and last values the body should see.
  • Changing a collection while looping over it. Adding or removing items during a for loop can skip items or repeat them. Loop over a copy, or build a new list.
  • Using while where for would do. A while loop that declares a counter, tests it and increments it is a for loop in disguise, and it has three places for a bug instead of one.

Which should you pick?

Ask one question: do I know what I am looping over before the loop starts? If yes, use a for loop. If the loop ends because of something that happens during the loop, use a while loop. When both would work, choose the one that puts the stopping rule where a reader will see it first.

Frequently asked questions

Can every for loop be rewritten as a while loop?
Yes. A for loop is a while loop with the setup, the condition and the update gathered in one place. In JavaScript, for (init; condition; afterthought) behaves like putting init before a while (condition) loop and the afterthought at the end of the body, with one exception: a continue statement in the for version still runs the afterthought, while in the hand-written while version it would skip it.
Which is faster, a for loop or a while loop?
For equivalent logic there is no meaningful difference to plan around. The documentation for both languages describes them as control-flow constructs, not as performance choices. Pick the one that states your intent more clearly, and measure with a profiler if a loop is actually slow.
Does a while loop always run at least once?
No. A while loop tests its condition before each pass, including the first, so if the condition is false at the start the body never runs. A do...while loop, available in JavaScript, C, Java and C#, tests after each pass and always runs at least once. Python has no do...while.
What happens if a while loop's condition never becomes false?
The loop never ends on its own, which is an infinite loop. Programs do this deliberately with while (true) and leave through break or return. If it is an accident, the usual cause is that nothing inside the body changes the variable the condition tests.

Sources