HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

JavaScript Loop While

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

The while loop loops through a block of code as long as a specified condition is true.

while (condition) {
  // code block to be executed
}

Example: Counting to 4

let i = 0;
while (i < 5) {
  console.log("The number is " + i);
  i++; // Don't forget to increment!
}
Danger: If you forget to increment the variable used in the condition, the loop will never end. This will crash your browser or server.

The Do While Loop

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);

Example: Guaranteed Execution

let i = 10;
do {
  console.log("I ran once even though 10 is not < 5");
  i++;
}
while (i < 5);

Comparing While and For

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.


Key Points to Remember

  • while checks the condition before the code runs
  • do...while runs the code at least once before checking
  • Always ensure your condition will eventually become false to avoid infinite loops
  • Handy for reading streams or processing data until an "End Of File" (EOF) marker is reached
  • The counter must be initialized outside the while loop