Loops can execute a block of code as long as a specified condition is true. The
while loop is perfect when you don't know exactly how many times the loop
should run beforehand.
The while loop loops through a block of code as long as a
specified condition is true.
while (condition) {
// code block to be executed
}
let i = 0;
while (i < 5) {
console.log("The number is " + i);
i++; // Don't forget to increment!
}
The do...while loop is a variant of the while loop. This loop will execute the
code block once, before checking if the condition is true, and then it
will repeat the loop as long as the condition is true.
do {
// code block to be executed
}
while (condition);
let i = 10;
do {
console.log("I ran once even though 10 is not < 5");
i++;
}
while (i < 5);
If you already know how many times the loop should run, use for. If you are
waiting for a dynamic change (like a user clicking a button or a file loading), use
while.
while checks the condition before the
code runsdo...while runs the code at least once
before checking