JavaScript While Loop
The while loop loops through a block of code as long as a specified condition is true. Use it when you don't know in advance how many iterations you need.
The while Loop
Basic while Loop
let i = 0;
while (i < 5) {
console.log("i =", i);
i++; // always increment, or the loop runs forever!
}The do...while Loop
The do...while loop executes the code block at least once before checking the condition.
do...while Loop
let i = 0;
do {
console.log("i =", i);
i++;
} while (i < 5);
// Even if condition is false from start, it runs once:
let x = 10;
do {
console.log("Runs at least once, x =", x);
} while (x < 5);| Loop | Condition Checked | Minimum Runs |
|---|---|---|
| while | Before each loop | 0 (may never run) |
| do...while | After each loop | 1 (always runs once) |
break and continue
Use break to exit a loop early. Use continue to skip the current iteration and go to the next.
break and continue
// break: exits the loop entirely
for (let i = 0; i < 10; i++) {
if (i === 5) break;
console.log("break demo — i:", i);
}
// continue: skips even numbers
for (let i = 0; i < 6; i++) {
if (i % 2 === 0) continue;
console.log("continue demo — odd i:", i);
}Practical Example — Search Loop
Find First Match
const numbers = [4, 7, 2, 9, 1, 5, 8];
const target = 9;
let found = false;
let idx = 0;
while (idx < numbers.length) {
if (numbers[idx] === target) { found = true; break; }
idx++;
}
console.log(found
? "Found " + target + " at index " + idx
: "Not found");📝 Note: Always ensure the condition will eventually become false or use break — an infinite loop freezes the browser tab.
Exercise:
When is the condition checked in a do...while loop?