A while loop repeats as long as its condition stays true. Use it when you do not know in advance how many passes you will need, only when to stop: keep rolling until you get a six, keep asking until the answer is valid. JavaScript has two versions: while and do...while.
while (condition) {
// code block to be executed
}
let i = 0;
while (i < 3) {
console.log("i is " + i);
i++;
}
The same three parts from a for loop are still here, just spread out: the start is above the loop, the condition is in the parentheses, and the change is inside the body.
i++) inside a while loop is the number one cause of infinite loops. The condition never becomes false, and the tab freezes. A for loop's one-line header makes this mistake harder; while makes it easy.
This is where while earns its place. How many times do you halve 1000 before it drops below 1?
let value = 1000;
let steps = 0;
while (value >= 1) {
value /= 2;
steps++;
}
console.log("Took " + steps + " steps");
Another classic: rolling a die until you get a six. There is no way to know in advance how many rolls it will take.
let roll = 0;
let tries = 0;
while (roll !== 6) {
roll = Math.floor(Math.random() * 6) + 1; // random 1 to 6
tries++;
}
console.log("Rolled a six after " + tries + " tries");
Here the "change" is not a counter at all: it is roll getting a new random value each pass. Any loop is safe as long as something in it can eventually make the condition false.
A while loop checks its condition before each pass, including the first. If the condition is false from the start, the body never runs at all:
let fuel = 0;
while (fuel > 0) {
console.log("Driving...");
fuel--;
}
// nothing prints
do...while flips the order: the body runs first, then the condition is checked. So the body always runs at least once, even if the condition is false from the start:
do {
// code block to be executed
} while (condition);
let fuel = 0;
do {
console.log("Engine check");
fuel--;
} while (fuel > 0);
do...while fits "try something, then decide whether to try again" situations, like asking for input and repeating the question only if the answer was invalid. Notice the semicolon after while (...) at the end: do...while is the only loop that ends with one. And like any while, do not forget the line that changes the condition.
A while loop is really a for loop with the start and change parts moved out of the header. These two do exactly the same thing:
for (let i = 0; i < 5; i++) {
console.log(i);
}
let j = 0;
while (j < 5) {
console.log(j);
j++;
}
Here is another pairing you will see. Since reading past the end of an array gives undefined, which is falsy, you can loop "while there is still an item":
const cars = ["BMW", "Volvo", "Saab", "Ford"];
let i = 0;
let text = "";
while (cars[i]) { // same as: for (; cars[i]; )
text += cars[i] + " ";
i++;
}
console.log(text);
while (list[i]) stops at the first falsy item, not just at the end. For [3, 0, 5] it stops at the 0 and never reaches the 5. The same goes for an empty string or null in the list. Unless you are sure no item can be falsy, use i < list.length instead.
for. Waiting for something to happen? Use while. Need the body to run at least once? Use do...while.
How many times does "hi" print?
let n = 10;
do {
console.log("hi");
n++;
} while (n < 5);
do...while runs its body before checking the condition. After that pass, 11 < 5 is false, so it stops. A plain while would print it zero times.What is wrong with this loop?
let count = 1;
while (count <= 5) {
console.log(count);
}
count, so count <= 5 is always true and the loop never ends (it prints 1 forever and freezes the tab). Add count++; inside the body.Which situation is the best fit for a while loop?
for territory.while loop that prints 1 through 5. Check that the counter changes inside the loop before you click Run: a loop that never ends freezes the tablet n = 1 and double it until it passes 1000. Count the stepswhile (nums[i]) on const nums = [3, 0, 5]; and see where it stops. Then fix it with i < nums.length