designwithfocus

Programming basics

For Loop vs While Loop: Which Repeater Fits the Job

By Design With Focus Team 8 min read
Two short code cards, one counting with for and one waiting on a while condition

Short answer

Use a for loop when the count or the collection is known, and a while loop when you stop only because a condition changes. JavaScript and Python both offer those two shapes. A for loop walks a range or a sequence. A while loop tests a condition before each pass, and it might never run, or it might not have a fixed end.

Last verified against the sources listed below.

Key takeaways

  • MDN's for loop runs an initializer, tests a condition, runs the body, then runs the afterthought.
  • A while loop tests first. MDN's sample stops once n is no longer less than 3.
  • Python's for walks items in a sequence. range(5) produces 0, 1, 2, 3, and 4.
  • Python's while repeats while the expression stays true, and it skips the body if the test starts false.
  • Neither loop is a speed ranking. Pick the one that matches what you know before the first pass.

A for loop vs while loop decision is about what you know before the first pass, not about which keyword is faster. MDN’s loops guide says every loop repeats an action some number of times, and that the mechanisms differ in how they pick the start and the end.

Use for when you have a count or a collection. Use while when you repeat until a condition changes.

The same split shows up in Python, with different spelling. The Python tutorial teaches for as a walk over a sequence. The language reference says while repeats as long as an expression is true. If you are still placing these keywords among other styles of code, the programming paradigm guide is the wider map.

What does a JavaScript for loop do?

A JavaScript for loop repeats until its condition is false. MDN writes the header as initialization, condition, and afterthought.

The initializer runs once. The condition is tested.

If it is true, the body runs, the afterthought runs, and the condition is tested again.

MDN’s walking example is the whole idea in one header:

for (let step = 0; step < 5; step++) {
  console.log("Walking east one step");
}

That body runs 5 times, with step equal to 0, 1, 2, 3, and 4. The count is known before the loop starts.

A counted task, such as turning a row of pixel values into another unit on paper, has the same shape. The PX to REM Converter does the unit change.

The loop, if you are practicing, is just the repetition.

MDN’s other classic for walks a list by index. It sets i to 0, continues while i is less than the number of options, and adds 1 after each pass. When the collection’s length is the bound, for still fits, because the end is known at the start of each check.

What does a JavaScript while loop do?

A while loop runs its body only while a condition stays true, and the test comes first. MDN’s first sample is short enough to trace by hand:

let n = 0;
let x = 0;
while (n < 3) {
  n++;
  x += n;
}

After the first pass, n is 1 and x is 1. After the second, n is 2 and x is 3.

After the third, n is 3 and x is 6. The test n < 3 is then false, so the loop stops.

You did not write the number 3 as a trip count in the header. You wrote the condition that ends the work.

do...while is the variant that always runs the body once before the test. MDN’s sample starts i at 0, adds 1, prints, and repeats while i < 5, so the printed values are 1 through 5. Reach for that only when the first pass must happen even if the condition is already false.

MDN’s warning is blunt: if the condition never becomes false, the loop does not end. while (true) with no break is the textbook infinite loop. A while is the right tool when the end depends on an event you can update inside the body, such as input arriving or a value crossing a limit. It is the wrong tool if you only forgot to write a counter.

How does Python spell each loop?

Python’s for walks items, and Python’s while watches a condition. The tutorial’s sequence example is a list of words. for w in words prints each word and its length, in list order. There is no index unless you ask for one.

When you do want numbers, range builds an arithmetic progression. range(5) yields 0, 1, 2, 3, and 4. The tutorial is explicit that the end point is never part of the sequence, and that range(10) produces 10 values, the legal indexes for a sequence of that length. You can also set a start and a step, as in range(0, 10, 3).

The introductory chapter shows while with a Fibonacci pair. a and b start at 0 and 1.

While a < 10, the loop prints a and then shifts the pair forward. The printed values are 0, 1, 1, 2, 3, 5, and 8.

The next a would be 13, so the test fails and the loop stops. The number of lines is whatever the condition allows, not a count you typed in the header.

The language reference adds the edge case. while tests the expression and runs the suite only if it is true.

If the expression is false the first time, the suite does not run. A break in the suite leaves the loop without running an else clause attached to the loop.

A continue skips the rest of the suite and goes back to the test.

ECMA-262 specifies the JavaScript form as while ( Expression ) Statement. Its evaluation repeats, reads the expression, and if ToBoolean of that value is false, the loop returns. Python and JavaScript disagree on indentation versus braces. They agree that while is a test, then a body.

Which repeater fits the job?

Match the loop to the thing that should stop it. The count, the collection, or a condition you update are the three honest choices.

Situation Use Why the docs point there
A known number of passes JavaScript for, or Python range The end is in the header or the range
Every item in a list or string Python for, or JavaScript for...of The collection is the sequence
Stop when a value changes while The test is the stopping rule
Body must run before the first test JavaScript do...while MDN runs the statement once first
The test may already be false while The body is skipped

A Stanford CS106B lecture, which is about counting work rather than about syntax, says a loop that does one more iteration for each extra element is linear. That is a reason to prefer a counted for when the collection length is the bound.

It is not a claim that while is slower. This article does not rank the two on speed.

JavaScript can express either pattern.

Python can express either pattern too. The fit is the question.

Which mistakes do the manuals flag?

Four mistakes show up in the official examples, and each one is a logic bug rather than a style nit.

Python says code that modifies a collection while iterating over that same collection is tricky. The tutorial’s fix is to loop over a copy, or to build a new collection. Deleting from the dict you are walking is the case to avoid.

JavaScript’s for...in is a poor array loop. MDN shows an array with an extra property.

for...in visits the indexes and that extra name. for...of visits the three values.

If you meant “each element,” use for...of or a numeric for.

continue does not mean “start the whole program over.” In a for loop, MDN says it jumps to the afterthought, so the counter still advances. In a while loop, it jumps to the condition. If you continue before you update the variable the condition depends on, you can spin forever. Put the update where both the normal path and the skip path will reach it.

break without a label ends only the innermost loop. MDN’s nested sample uses a label when the outer loop must stop too. Python’s break also ends the innermost for or while. If the search is done, break is clearer than twisting the condition into an early false.

Write the stopping rule in the place a reader expects. A known count belongs in for or range.

A condition that changes inside the body belongs in while. If you cannot point to the line that makes the test false, you do not have a loop yet.

You have an infinite one.

Frequently asked questions

Does a while loop always run at least once?

No. MDN says the while test happens before the body. If the condition is false on the first check, the body never runs. The loop that does run once before testing is do...while. In MDN's sample, i starts at 0, the body adds 1 and prints, and the test i < 5 happens after that print. Python's language reference describes the same while rule: the suite runs only when the expression is true, and a false result on the first test ends the loop.

Why does Python's for loop look different from JavaScript's?

The Python tutorial says its for statement iterates over the items of any sequence, in order, rather than making you supply a counter, a test, and a step the way C does. A list of words is enough. When you do need numbers, range generates them. The end value is not included, so range(5) has five values, 0 through 4. JavaScript's for header is the C-shaped one MDN documents: initialization, condition, and afterthought.

What does for...in do that for...of does not?

MDN says for...in walks the enumerable property names of an object. On an array, that includes the indexes and also any extra properties you added. In the docs' sample, an array of 3, 5, and 7 with a property named foo logs the names 0, 1, 2, and foo. for...of on the same array logs the values 3, 5, and 7, and it does not log foo.

Can the body of a for loop run zero times?

Yes. MDN's loops chapter says every loop repeats an action some number of times, and that number can be zero. In a for loop, the condition is checked before the body. If it is false immediately, the body is skipped. Omitting the condition entirely is different: MDN says a missing condition is treated as true, which is how a for loop can be written so it never stops on its own. A normal counted loop avoids that by keeping a test that eventually fails.

Where do break and continue go?

MDN says break without a label ends the innermost while, do...while, for, or switch, and continues after that statement. continue ends only the current pass. In a while loop it jumps back to the condition. In a for loop it jumps to the afterthought, so the counter still updates. Python's tutorial uses the same two words for the innermost for or while. continue goes to the next cycle. A break inside a nested loop ends only that inner loop unless you have structured the code another way.

Sources