While and Do...While Loops
Loops are useful when we want to repeat something again and again. In JavaScript, the while
and do...while
loops are perfect when we don’t know exactly how many times we need to repeat something — we just keep looping as long as a condition is true.
while vs do...while
The while
loop checks the condition before running the code block. If the condition is true, it runs the code inside. It keeps repeating as long as the condition remains true.
let i = 0;
while (i < 3) {
console.log(i);
i++;
}
This will print 0
, 1
, and 2
. The loop checks if i < 3
before each run.
The do...while
loop is slightly different. It runs the code once first, and then checks the condition. This means the code will always run at least once, even if the condition is false at the beginning.
let i = 0;
do {
console.log(i);
i++;
} while (i < 3);
This also prints 0
, 1
, and 2
, but it guarantees that the code block runs once before checking.
Avoiding Infinite Loops
An infinite loop is a loop that never ends. This can happen if the condition never becomes false. Infinite loops can crash your browser or freeze your computer, so it's important to avoid them.
Here’s an example of an infinite loop:
let i = 0;
while (i < 5) {
console.log(i);
// i++ is missing here
}
Since i
never increases, i < 5
is always true, and the loop never stops.
To avoid infinite loops:
- Always make sure the loop condition will eventually become false.
- Be sure to update the variable inside the loop (like
i++
). - Use
break
to stop the loop if needed.
Real-Life Example
Let’s say we want to ask a user for a number greater than 10. We don’t know how many times they’ll enter a wrong number, so we use a loop.
let number;
do {
number = prompt("Enter a number greater than 10:");
} while (number <= 10);
This keeps asking until the user enters something greater than 10. This is a good example of when do...while
is useful.