JAVASCRIPT • CONTROL FLOW

For/While/Do-While Loops — Use for/while/do-while loops appropriately

Master the three loop structures in JavaScript to repeat code efficiently and choose the right loop for every situation.

Historical Context & Motivation

Imagine you had to write console.log("Hello") one thousand times—line after line of the exact same statement. That would be absurd, right? Early programmers faced exactly this problem. Before loops existed, repeating an instruction meant literally duplicating code. Loops solved this by letting a computer execute a block of code over and over until a condition tells it to stop. The idea of repetition in computing stretches back to the very first machines and has evolved alongside programming languages for decades.

1843
Ada Lovelace's Algorithm
Ada Lovelace wrote the first algorithm for Charles Babbage's Analytical Engine, which included the concept of a loop—a set of instructions that repeats. This is widely considered the birth of the loop in computing.
1957
FORTRAN Introduces the DO Loop
IBM's FORTRAN language introduced the DO loop, giving programmers a formal, structured way to repeat code a specific number of times. This became the ancestor of the modern for loop.
1972
C Language Defines Three Loop Types
The C programming language, created by Dennis Ritchie, established the for, while, and do-while loop structures that nearly every language since—including JavaScript—has adopted.
1995
JavaScript Is Born
Brendan Eich created JavaScript in just ten days at Netscape. He borrowed C-style loop syntax directly, giving web developers for, while, and do...while loops from day one.
2015
ES6 Adds for...of
ECMAScript 2015 (ES6) introduced the for...of loop for iterating over arrays and other iterable objects, expanding the loop toolkit while keeping the classic three structures intact.

The central question that loops answer is deceptively simple: How do you tell a computer to do the same thing many times without writing redundant code? JavaScript gives you three classic tools to answer that question—for, while, and do...while—each designed for slightly different situations. Knowing when to reach for each one is what separates a beginner from a confident programmer.

Core Principles & Definitions

Every loop in JavaScript shares three essential ingredients. First, you need an initialization—a starting point, like setting a counter to zero. Second, you need a condition—a true-or-false test that decides whether the loop keeps running. Third, you need an update (sometimes called the iteration step)—something that changes each cycle so the condition eventually becomes false and the loop stops. If you forget the update, you get an infinite loop, which freezes your program.

1

for Loop

Best when you know in advance how many times to repeat. Initialization, condition, and update are all declared in one line inside the parentheses.
2

while Loop

Best when you don't know how many iterations are needed. The condition is checked before each iteration. If it starts false, the body never runs.
3

do...while Loop

Guarantees the body runs at least once because the condition is checked after each iteration, not before. Ideal for menus and user-input prompts.
4

Loop Body

The block of code inside the curly braces { } that executes on each iteration. It can contain any valid JavaScript—assignments, function calls, even other loops (nested loops).
5

Infinite Loop

A loop whose condition never becomes false. This causes the program to hang. Always ensure your update moves the loop toward its termination condition.
✦ KEY TAKEAWAY
Think of a loop like a track runner doing laps. The initialization is the starting line, the condition is the coach shouting "keep going!" or "stop!", and the update is each completed lap being counted. A for loop is like being told to run exactly 10 laps. A while loop is like running until the coach says stop. A do...while loop is like always running at least one lap, then checking if you should continue.

Visual Explanation — Loop Flow

The diagram below shows how each of the three loop types flows from start to finish. Pay close attention to where the condition check happens relative to the loop body—that single difference is what makes each loop unique.

All three loops share initialization, condition, body, and update phases. The for and while loops check the condition before running the body (they might run zero times), while do...while checks afterward, guaranteeing at least one execution.

In the diagram, notice how the for loop has a dedicated "Initialize" step at the top—that's the let i = 0 part of the syntax. The while loop jumps straight to the condition, meaning you must initialize your variable separately before the loop begins. The do...while loop is the most distinctive: the body executes first, then the condition is tested. This is why it always runs at least once, even if the condition is false from the start.

How Each Loop Works — Syntax Deep Dive

The for Loop Syntax

The for loop packs three expressions into a single line, separated by semicolons. The general form is: for (initialization; condition; update) { body }. The initialization runs once before the first iteration. The condition is evaluated before each iteration—if it's true, the body runs; if false, the loop exits. After each body execution, the update expression runs, and the condition is checked again.

FOR LOOP PATTERN
for (let i = 0; i < n; i++) { /* body */ }
let i = 0 — initialization (counter starts at 0). i < n — condition (loop runs while i is less than n). i++ — update (increment i by 1 after each iteration). The body runs exactly n times.

The while Loop Syntax

The while loop is the simplest form. You write while (condition) { body }. The initialization and update must be handled manually—you declare and set the variable before the loop, and you update it inside the body. This makes while flexible but also means you must be more careful to avoid infinite loops.

WHILE LOOP PATTERN
let i = 0; while (i < n) { /* body */ i++; }
Initialization happens before the loop. The condition i < n is checked first—if false initially, the body never executes. The update i++ must appear inside the body or the loop will never end.

The do...while Loop Syntax

The do...while loop flips the condition check to the end. You write do { body } while (condition);. Notice the semicolon after the closing parenthesis—it's required. Because the body runs before the condition is ever tested, this loop guarantees at least one execution. This makes it ideal for situations like asking a user for input and re-prompting if the input is invalid.

DO...WHILE LOOP PATTERN
let i = 0; do { /* body */ i++; } while (i < n);
The body executes first, then i < n is evaluated. Even if n is 0 or negative, the body runs once.

Choosing the Right Loop — Decision Guide

Picking the right loop isn't about memorizing rules—it's about asking yourself a few simple questions. Do you know how many times the code needs to repeat? Is there a situation where the body might not need to run at all? Or must it run at least once? The decision flowchart below walks you through these questions.

Use this decision tree: if you know the count, pick for. If the count is unknown and the body must run at least once, pick do...while. If the count is unknown and the body might not run at all, pick while.
Common scenarios and the recommended loop type
ScenarioBest LoopWhy
Print numbers 1 through 10forYou know exactly how many iterations (10).
Read user input until they type "quit"whileUnknown count; the user might type "quit" immediately.
Show a menu, then re-show if choice is invaliddo...whileThe menu must display at least once before checking.
Loop through all items in an arrayforArray length gives you a known count.
Roll a die until you get a 6do...whileYou must roll at least once; unknown how many rolls.

Worked Example — Summing Numbers with Each Loop

Let's solve the same problem—adding up all integers from 1 to 5—using each of the three loops. This lets you see how the syntax differs while the result stays the same. The expected output is 1 + 2 + 3 + 4 + 5 = 15.

Sum 1 to 5 Using a for Loop
1
Step 1 — Declare a sum variableCreate a variable let sum = 0; to accumulate the total.
2
Step 2 — Write the for loopSet up initialization let i = 1, condition i <= 5, and update i++. Inside the body, add i to sum: for (let i = 1; i <= 5; i++) { sum += i; }
3
Step 3 — Trace the iterationsIteration 1: i=1, sum=0+1=1. Iteration 2: i=2, sum=1+2=3. Iteration 3: i=3, sum=3+3=6. Iteration 4: i=4, sum=6+4=10. Iteration 5: i=5, sum=10+5=15. Now i becomes 6, condition 6 <= 5 is false, so the loop exits.
sum = 15
Sum 1 to 5 Using a while Loop
1
Step 1 — Initialize before the looplet sum = 0; let i = 1; — both the accumulator and the counter are declared outside.
2
Step 2 — Write the while loopwhile (i <= 5) { sum += i; i++; } — the update i++ is inside the body. Forgetting it would create an infinite loop.
3
Step 3 — VerifyThe same five iterations occur, producing the same result.
sum = 15
Sum 1 to 5 Using a do...while Loop
1
Step 1 — Initializelet sum = 0; let i = 1;
2
Step 2 — Write the do...while loopdo { sum += i; i++; } while (i <= 5); — the body runs first, adding 1 to sum before any condition check.
3
Step 3 — Trace the key differenceAfter the body runs the 5th time (i was 5, sum becomes 15), the update makes i = 6. The condition 6 <= 5 is false, so the loop ends. If we had started with i = 10, the body would still run once (adding 10), unlike a while loop which would skip entirely.
sum = 15

Strengths & Limitations of Each Loop

All three loops are equally powerful—any task solvable by one can technically be done by the others. However, choosing the right loop improves readability and reduces the chance of bugs. The table below highlights where each loop shines and where it can trip you up.

Side-by-side comparison of the three JavaScript loop types
Featureforwhiledo...while
Clarity of countExcellent — count is visible in the headerModerate — count logic is scatteredModerate — count logic is scattered
Minimum runs0 (condition checked first)0 (condition checked first)1 (body runs before check)
Risk of infinite loopLow — update is in the headerHigher — update must be in bodyHigher — update must be in body
Best forArrays, counting, known rangesEvent-driven, sentinel values, file readingMenus, input validation, games
Scope of counterCounter is scoped to loop (with let)Counter exists outside the loopCounter exists outside the loop
✦ KEY TAKEAWAY
Think of for as a GPS with a set destination—you know exactly where you're going and how many turns to take. while is like driving until you see a gas station—you don't know how far it is, and maybe one is right around the corner (zero iterations). do...while is like trying a restaurant at least once before deciding if you'll go back.

Connection to Advanced Iteration Techniques

Once you're comfortable with for, while, and do...while, you'll encounter more specialized iteration methods in JavaScript. These include for...of for iterating over arrays and strings, for...in for iterating over object properties, and powerful array methods like .forEach(), .map(), and .filter(). All of these are built on the same loop logic you've learned here.

How classic loops relate to modern JavaScript iteration patterns
Classic LoopModern AlternativeWhen to Upgrade
for (let i = 0; i < arr.length; i++)for (const item of arr)When you don't need the index—just the values
for loop with push()arr.map(item => transform(item))When you want to create a new array by transforming each element
for loop with if + push()arr.filter(item => condition)When you want to keep only items matching a condition
while with async operationsfor await...ofWhen iterating over asynchronous data streams
🔮 Looking Ahead
Understanding the three basic loops builds the mental model for recursion—a technique where a function calls itself, creating a different kind of repetition. Many problems that can be solved with loops can also be solved recursively, and vice versa. You'll explore recursion in later courses, and when you do, your loop instincts will transfer directly.

Practice Problems

PROBLEM 1 — CONCEPTUAL
What is the fundamental difference between a while loop and a do...while loop? Give a real-world scenario where this difference matters.
PROBLEM 2 — BASIC CALCULATION
Write a for loop that calculates the product of all integers from 1 to 6 (i.e., 6 factorial). What value does product hold after the loop finishes?
PROBLEM 3 — INTERMEDIATE
Convert the following for loop into an equivalent while loop: for (let i = 10; i >= 0; i -= 2) { console.log(i); }. Then list all values printed.
PROBLEM 4 — APPLIED
You're building a simple number-guessing game. The computer picks a secret number (say, 7). The user guesses repeatedly until correct. Which loop type is most appropriate, and why? Write the loop structure using pseudocode or JavaScript (you can use prompt() for input).
PROBLEM 5 — CRITICAL THINKING
A student writes: for (let i = 1; i <= 10; i++) { if (i % 3 === 0) continue; if (i === 8) break; console.log(i); }. Predict exactly which values are printed and explain how continue and break alter normal loop behavior.

Lesson Summary

JavaScript provides three fundamental loop structures for repeating code. The for loop is best when you know the exact number of iterations—its header bundles initialization, condition, and update into one clean line. The while loop checks its condition before each iteration and is ideal when the number of repetitions is unknown and the body might not run at all. The do...while loop checks its condition after each iteration, guaranteeing the body runs at least once—perfect for menus and input validation.

Every loop requires all three ingredients—initialization, condition, and update—to avoid infinite loops. The keywords break and continue give you additional control: break exits a loop entirely, while continue skips to the next iteration. Mastering these three loop types prepares you for modern JavaScript iteration tools like for...of, .map(), .filter(), and eventually recursion.

Varsity Tutors • JavaScript • For/While/Do-While Loops