Repeat Statements (Loops)
Learning Objectives
- Master
whileloops for repetition - Learn
forloops for controlled iteration - Understand loop control with
breakandcontinue - Recognize common loop mistakes
- Apply loops to solve real problems
Section 5.1: The While Loop
What is a Loop?
A loop repeats a block of code multiple times until a condition becomes false.
While Loop Syntax
while (condition) {
// Code to repeat
}
Simple Example
let count = 1;
while (count <= 5) {
console.log(count);
count = count + 1;
}
// Output:
// 1
// 2
// 3
// 4
// 5
Real-World Example: Password Validation
let password = "";
while (password !== "secret123") {
password = prompt("Enter password:");
}
console.log("Access granted!");
Infinite Loops (Avoid!)
while (true) {
console.log("This never stops!");
// ❌ DANGEROUS: Freezes the browser
}
Loop with Break
let attempt = 0;
while (true) {
attempt++;
let password = prompt("Enter password:");
if (password === "secret123") {
console.log("Correct!");
break; // Exit the loop
}
if (attempt === 3) {
console.log("Too many attempts");
break;
}
}
Section 5.2: The For Loop
For Loop Syntax
for (initialization; condition; increment) {
// Code to repeat
}
Simple For Loop
for (let i = 1; i <= 5; i++) {
console.log(i);
}
// Output: 1, 2, 3, 4, 5
Breaking It Down
for (let i = 1; // Initialize counter
i <= 5; // Repeat while true
i++ // Increment each iteration
) {
console.log(i);
}
Counting Backwards
for (let i = 5; i >= 1; i--) {
console.log(i);
}
// Output: 5, 4, 3, 2, 1
Skipping Values
for (let i = 0; i <= 10; i += 2) {
console.log(i); // 0, 2, 4, 6, 8, 10
}
Using continue
Skip to the next iteration:
for (let i = 1; i <= 5; i++) {
if (i === 3) {
continue; // Skip 3
}
console.log(i); // 1, 2, 4, 5
}
Section 5.3: Common Mistakes
Mistake 1: Infinite Loops
// ❌ Wrong: condition never becomes false
let i = 0;
while (i < 10) {
console.log(i);
// forgot to increment i
}
// ✅ Correct
let i = 0;
while (i < 10) {
console.log(i);
i++; // Increment
}
Mistake 2: Off-by-One Error
// ❌ Wrong: prints 1-4 instead of 1-5
for (let i = 1; i < 5; i++) {
console.log(i);
}
// ✅ Correct
for (let i = 1; i <= 5; i++) {
console.log(i);
}
Mistake 3: Wrong Condition Check
// ❌ Wrong: loop never executes
for (let i = 10; i < 5; i++) {
console.log(i);
}
// ✅ Correct
for (let i = 1; i < 10; i++) {
console.log(i);
}
Mistake 4: Modifying Loop Variable Incorrectly
// ❌ Wrong: changes step size unexpredictably
for (let i = 0; i < 10; i++) {
i++; // Skips every other number
}
// ✅ Correct
for (let i = 0; i < 10; i = i + 2) {
console.log(i); // 0, 2, 4, 6, 8
}
Section 5.4: Which Loop to Use?
Use while When:
- You don't know how many iterations you need
- Condition is complex
- Loop might not execute at all
while (userInput !== "quit") {
userInput = prompt("Enter command:");
}
Use for When:
- You know the exact number of iterations
- You need a counter
- Iterating through a range
for (let i = 1; i <= 100; i++) {
console.log(i);
}
Coding Challenges
Challenge 5.1: Carousel
Task: Create a rotating carousel that displays numbers 1-5 repeatedly, 3 times total
Expected Output:
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
Challenge 5.2: Use of Modulo Operator
Task: Print numbers 1-20, but:
- Say "Fizz" for multiples of 3
- Say "Buzz" for multiples of 5
- Say "FizzBuzz" for multiples of both
Challenge 5.3: Input Validation
Task: Ask user to enter a number between 1 and 10
- Keep asking until valid input is provided
- Show error message for invalid input
Challenge 5.4: Multiplication Table
Task: Create a multiplication table for a given number
Example for 5:
5 × 1 = 5
5 × 2 = 10
5 × 3 = 15
...
5 × 10 = 50
Challenge 5.5: Neither Yes nor No
Task: Ask user yes/no questions until they give the correct answer
- Keep asking until "yes" is entered
- Count the number of attempts
Challenge 5.6: FizzBuzz
Task: Print numbers 1-100 with special rules:
- "Fizz" for multiples of 3
- "Buzz" for multiples of 5
- "FizzBuzz" for multiples of both
- Otherwise print the number
Key Takeaways
✅ while loops repeat while a condition is true
✅ for loops are best for counting/iteration
✅ Use break to exit a loop early
✅ Use continue to skip to next iteration
✅ Avoid infinite loops by always update loop variables
✅ Be careful with off-by-one errors
Quiz Questions
- What's the difference between
whileandforloops? - How do you exit a loop early?
- What does
i++do? - Explain an off-by-one error
- What would
for (let i = 0; i < 5; i++)print?
Next Module: Module 6 - Write Functions