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.
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.
Why Use Loops?
JavaScript's Three Loop Types
Anatomy of a for Loop
The while Loop
The do...while Loop
while vs. do...while: The Key Difference
How to Choose the Right Loop
Example: Summing with for
Calculate the sum \( \displaystyle\sum_{i=1}^{n} i \) for \( n = 5 \):
Example: Halving with while
Keep halving a number until it drops below \( 1 \). We don't know in advance how many iterations this takes:
Example: Input Validation with do...while
Ask for a password until the user enters the correct one. The prompt must appear at least once:
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}} \).
break and continue
Common Mistakes
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?