While and Do-While Loops
Looping Without a Set Count
While the for loop is great when you know the exact number of times you want to loop, sometimes you need a loop to run an unknown number of times—specifically, "while" a certain condition remains true.
The while Loop
The while loop evaluates a condition before every single iteration. If the condition is true, it runs the block of code.
let count = 1;
while (count <= 3) {
console.log("Count is: " + count);
count++; // CRITICAL: You must update the variable, or it loops infinitely!
}
Warning: Infinite loops! If you forget to include count++, the condition (1 <= 3) will always be true, and your browser will freeze or crash trying to run the loop forever.
The do...while Loop
This is a variation of the while loop. The crucial difference is that a do...while loop will ALWAYS execute its code block at least once, even if the condition is false from the very beginning. It checks the condition after the code runs.
let password = "wrong";
do {
console.log("Attempting to login...");
// Imagine code here that asks the user for a password
} while (password === "correct");
// It prints the log once, then checks the condition, sees it is false, and stops.
When to use which?
- Use a
forloop when you know exactly how many times to loop (e.g., looping through 10 items). - Use a
whileloop when you want to loop until a condition changes, and it's okay if it never runs at all. - Use a
do...whileloop when you absolutely must run the code at least once before checking the condition.
💡 Himanshu's Tip:
If your browser tab suddenly freezes and crashes while you are practicing loops, congratulations—you just wrote your first Infinite Loop! Always double-check that your condition will eventually become false before hitting save.
Interview Questions
- What is the primary difference between a
whileloop and aforloop? - How is a
do...whileloop different from a standardwhileloop? - What causes an infinite loop?