Example 1 — Body may never run
If the condition starts false, skip the body.
JavaScript
let n = 0;
while (n > 0) console.log("hi");
console.log("done"); How It Works
- Condition is false immediately.
- Only done prints.
while checks a condition first, then runs the body. It keeps going until the condition becomes falsy. Make sure something inside the loop moves toward stopping.
let n = 3;
while (n > 0) {
console.log(n);
n--;
} If the condition starts false, skip the body.
let n = 0;
while (n > 0) console.log("hi");
console.log("done"); Keep going until a flag changes.
let left = 2;
while (left) {
console.log("tick");
left--;
} Use do...while instead.
console.log("see do...while page"); CODETOFUN NEWS
Get the latest IT news, programming updates, and technology trends directly on your phone.
Your daily dose of tech, straight to your feed.
6 people found this page helpful