01 / 21

For / While / Do-While
Loops in JavaScript

Master the three fundamental loop structures that let you repeat code efficiently, iterate over data, and build dynamic programs.

JavaScript

What Is a Loop?

A loop is a control structure that repeats a block of code as long as a specified condition remains true. Instead of writing the same statement \( n \) times, a loop executes it \( n \) times automatically.

Start Condition true? Yes Run Code Repeat No End

Why Use Loops?

★ Reduce Repetition
Write code once and run it \( n \) times instead of copy-pasting the same lines.
★ Process Collections
Iterate over arrays, strings, and objects to transform or inspect every element.
★ Dynamic Behavior
Repeat until a user-defined condition is met: input validation, animations, game ticks.

JavaScript's Three Loop Types

for
Best when you know how many times to iterate. Packs init, condition, and update in one line.
while
Best when the number of iterations is unknown. Checks the condition before each iteration.
do...while
Like while, but guarantees the body runs at least once. Checks condition after each iteration.

Anatomy of a for Loop

for (let i = 0; i < 5; i++) { console.log(i); } // Output: 0, 1, 2, 3, 4
INITIALIZATION let i = 0 CONDITION i < 5 UPDATE i++ Runs once Checked every loop Runs after body

The while Loop

let count = 0; while (count < 3) { console.log("Count is", count); count++; } // Output: Count is 0, Count is 1, Count is 2
1
Check condition before entering the loop body.
2
Execute body if the condition is true.
3
Update state inside the body (you must do this manually).
4
Repeat from step 1 until condition is false.

The do...while Loop

let input; do { input = prompt("Enter 'yes':"); } while (input !== "yes"); console.log("Thank you!");
Start Execute Body Condition true? Yes No Exit loop

while vs. do...while: The Key Difference

while (Pre-Check)
Condition checked before running the body. If false initially, body runs zero times.
do...while (Post-Check)
Body runs first, condition checked after. Body always runs at least once.
// while: body never runs let x = 10; while (x < 5) { console.log(x); } // No output // do...while: body runs once let y = 10; do { console.log(y); } while (y < 5); // Output: 10

How to Choose the Right Loop

1
Do you know the iteration count? If yes, use a for loop.
2
Is the count unknown but the body might not run? Use a while loop.
3
Must the body run at least once? Use a do...while loop.
4
Iterating over an array? A for loop (or for...of) is usually cleanest.

Example: Summing with for

Calculate the sum \( \displaystyle\sum_{i=1}^{n} i \) for \( n = 5 \):

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

Example: Halving with while

Keep halving a number until it drops below \( 1 \). We don't know in advance how many iterations this takes:

let value = 100; let steps = 0; while (value >= 1) { value /= 2; steps++; } console.log(steps); // 7

Example: Input Validation with do...while

Ask for a password until the user enters the correct one. The prompt must appear at least once:

const SECRET = "openSesame"; let attempt; do { attempt = prompt("Enter password:"); } while (attempt !== SECRET); console.log("Access granted!");

Nested Loops

A loop inside another loop. The inner loop runs to completion for each iteration of the outer loop. Total iterations: \( n_{\text{outer}} \times n_{\text{inner}} \).

for (let row = 1; row <= 3; row++) { let line = ""; for (let col = 1; col <= 3; col++) { line += (row * col) + " "; } console.log(line); } // 1 2 3 // 2 4 6 // 3 6 9

break and continue

break
Exits the entire loop immediately. No more iterations run.
continue
Skips the rest of the current iteration and jumps to the next one.
for (let i = 0; i < 10; i++) { if (i === 5) break; // stop at 5 if (i % 2 === 0) continue; // skip even numbers console.log(i); } // Output: 1, 3

Common Mistakes

✕ Infinite Loop
Forgetting to update the loop variable inside a while or do...while, so the condition never becomes false.
✕ Off-By-One Error
Using < vs. <= incorrectly: iterating \( n-1 \) or \( n+1 \) times instead of \( n \) times.
✕ Wrong Loop Type
Using while when do...while is needed (body must run once), or for when the count is truly unknown.

Comparison Summary

for while do...while
Condition check Before each pass Before each pass After each pass
Minimum runs \( 0 \) \( 0 \) \( 1 \)
Best for Known count Unknown count Run-at-least-once
Init/Update Built into syntax Manual Manual
Semicolon after? No No Yes: while(...);

Question 1 of 5

What is the output of this code?

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

Question 2 of 5

Which loop always executes its body at least once?

Question 3 of 5

What does continue do inside a loop?

Question 4 of 5

What is the value of count after this code runs?

let count = 0; while (count < 10) { count += 3; }

Question 5 of 5

Which loop type is best when you know exactly how many iterations you need?