Episode 17 of 46
While Loops
Learn how to repeat code with while and do...while loops.
Loops let you repeat a block of code multiple times. The while loop repeats as long as a condition is true.
Basic While Loop
let count = 1;
while (count <= 5) {
console.log("Count:", count);
count++;
}
// Output: Count: 1, Count: 2, ... Count: 5
How It Works
- Check the condition
- If true, run the code block
- Go back to step 1
- If false, exit the loop
Infinite Loop Warning
// DON'T DO THIS — infinite loop!
while (true) {
console.log("Forever...");
}
// Always make sure the condition will eventually become false!
Do...While Loop
The do...while loop runs the code at least once before checking the condition:
let num = 10;
do {
console.log("Number:", num);
num++;
} while (num <= 5);
// Output: "Number: 10" — runs once even though 10 > 5
Practical Example
// Simple guessing game concept
let secretNumber = 7;
let guess = 0;
let attempts = 0;
while (guess !== secretNumber) {
guess = Math.floor(Math.random() * 10) + 1;
attempts++;
}
console.log(`Found ${secretNumber} in ${attempts} attempts!`);