SECTION 1
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
1957 • FORTRAN Introduces the DO Loop
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
for, while, and do-while loop structures that nearly every language since—including JavaScript—has adopted.1995 • JavaScript Is Born
for, while, and do...while loops from day one.2015 • ES6 Adds for...of
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.
SECTION 2
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.
for Loop
while Loop
do...while Loop
Loop Body
{ } that executes on each iteration. It can contain any valid JavaScript—assignments, function calls, even other loops (nested loops).Infinite Loop
KEY TAKEAWAY
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.SECTION 3
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.
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.
SECTION 4
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
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
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
The body executes first, then i < n is evaluated. Even if n is 0 or negative, the body runs once.
SECTION 5
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.
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.| Scenario | Best Loop | Why |
|---|---|---|
| Print numbers 1 through 10 | for | You know exactly how many iterations (10). |
| Read user input until they type "quit" | while | Unknown count; the user might type "quit" immediately. |
| Show a menu, then re-show if choice is invalid | do...while | The menu must display at least once before checking. |
| Loop through all items in an array | for | Array length gives you a known count. |
| Roll a die until you get a 6 | do...while | You must roll at least once; unknown how many rolls. |
Common scenarios and the recommended loop type
SECTION 6
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 variable
Create a variablelet sum = 0;to accumulate the total. - 2
Step 2 — Write the for loop
Set up initializationlet i = 1, conditioni <= 5, and updatei++. Inside the body, add i to sum:for (let i = 1; i <= 5; i++) { sum += i; } - 3
Step 3 — Trace the iterations
Iteration 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, condition6 <= 5is false, so the loop exits.sum = 15
Sum 1 to 5 Using a while Loop
- 1
Step 1 — Initialize before the loop
let sum = 0; let i = 1;— both the accumulator and the counter are declared outside. - 2
Step 2 — Write the while loop
while (i <= 5) { sum += i; i++; }— the updatei++is inside the body. Forgetting it would create an infinite loop. - 3
Step 3 — Verify
The same five iterations occur, producing the same result.sum = 15
Sum 1 to 5 Using a do...while Loop
- 1
Step 1 — Initialize
let sum = 0; let i = 1; - 2
Step 2 — Write the do...while loop
do { sum += i; i++; } while (i <= 5);— the body runs first, adding 1 to sum before any condition check. - 3
Step 3 — Trace the key difference
After the body runs the 5th time (i was 5, sum becomes 15), the update makes i = 6. The condition6 <= 5is false, so the loop ends. If we had started withi = 10, the body would still run once (adding 10), unlike awhileloop which would skip entirely.sum = 15
SECTION 7
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.
| Feature | for | while | do...while |
|---|---|---|---|
| Clarity of count | Excellent — count is visible in the header | Moderate — count logic is scattered | Moderate — count logic is scattered |
| Minimum runs | 0 (condition checked first) | 0 (condition checked first) | 1 (body runs before check) |
| Risk of infinite loop | Low — update is in the header | Higher — update must be in body | Higher — update must be in body |
| Best for | Arrays, counting, known ranges | Event-driven, sentinel values, file reading | Menus, input validation, games |
| Scope of counter | Counter is scoped to loop (with let) | Counter exists outside the loop | Counter exists outside the loop |
Side-by-side comparison of the three JavaScript loop types
KEY TAKEAWAY
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.SECTION 8
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.
| Classic Loop | Modern Alternative | When 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 operations | for await...of | When iterating over asynchronous data streams |
How classic loops relate to modern JavaScript iteration patterns
Looking Ahead
SECTION 9
Practice Problems
Question 1: CONCEPTUAL
while loop and a do...while loop? Give a real-world scenario where this difference matters.Show answer
while loop checks its condition before executing the body, so it might never run if the condition is initially false. A do...while loop executes the body first and then checks the condition, guaranteeing at least one execution. A real-world example: a password prompt that must display at least once. You show the prompt (body), the user enters something, and then you check if it's correct (condition). If it's wrong, you loop back and ask again. A do...while fits perfectly because the prompt must appear before you can evaluate any answer.Question 2: BASIC CALCULATION
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?Show answer
let product = 1; for (let i = 1; i <= 6; i++) { product *= i; }. We start product at 1 (not 0, because multiplying by 0 would always give 0). Each iteration multiplies the running product by i: 1×1=1, 1×2=2, 2×3=6, 6×4=24, 24×5=120, 120×6=720. The final value is 720. This is 6! (six factorial), a common computation in combinatorics.Question 3: INTERMEDIATE
for loop into an equivalent while loop: for (let i = 10; i >= 0; i -= 2) { console.log(i); }. Then list all values printed.Show answer
let i = 10; while (i >= 0) { console.log(i); i -= 2; }. The initialization let i = 10 moves outside the loop, and the update i -= 2 moves inside the body. The printed values are: 10, 8, 6, 4, 2, 0. After printing 0, the update makes i = −2, and the condition -2 >= 0 is false, so the loop ends. This demonstrates that converting between loop types requires moving parts around but doesn't change the logic.Question 4: APPLIED
prompt() for input).Show answer
do...while loop is ideal because the player must guess at least once before we can check if they're correct. Example code: const secret = 7; let guess; do { guess = Number(prompt('Guess a number:')); if (guess !== secret) console.log('Try again!'); } while (guess !== secret); console.log('Correct!'); The body asks for a guess and gives feedback, then the condition checks if the guess matches. If it does, the loop exits and prints 'Correct!'. A while loop could also work, but you'd need to initialize guess to a dummy value first, making the code less clean.Question 5: CRITICAL THINKING
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.Show answer
continue skips the rest of the body, jumping back to the update/condition). i=4 (print 4). i=5 (print 5). i=6 (divisible by 3 → skip). i=7 (print 7). i=8 (break exits the loop entirely—nothing more is printed). The continue statement skips the remaining body for the current iteration but lets the loop keep going. The break statement terminates the loop immediately, regardless of the condition. These two keywords are valuable tools for fine-tuning loop behavior beyond the basic condition check.SUMMARY
Lesson Summary
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.