while & do..while Loops

sfrasica

Steven Frasica

Posted on July 9, 2020

while & do..while Loops

JavaScript has many tools and ways to complete iterations, some with interesting quirks to them. While loops are used to execute a statement or perform an action as long as the specified condition(s) remains true. A do...while loop will execute one time before checking if a condition is true. After executing one time, then it will continue to loop until the condition is no longer true.

While Loop

The counter variable is declared before the while loop statement.
The loop limiter or the condition is closed in parenthesis.
The code block enclosed in the curly braces will run while the counter is less than or equal to 5. The counter increments by 1 on each run.

let counter = 0;

while (counter <= 5) {

 alert(counter);

 counter++;
}

do...while loop

A do...while loop begins with the do keyword rather than while. The while clause is at the bottom of the statement.

let counter = 0;

do {

  alert(counter);

  counter++;


} while (counter <=5);



One notable difference between while and do...while loops is that the while loop may not necessarily ever execute its statement of code. This could be the case when the initial condition is never met. For example, if the loop is instructed to run as long as the variable counter is less than 5, but the variable counter is equal to 6, then that code block will never execute.

A do...while loop on the other hand will execute the code block at least one time before checking if the condition is true to continue execution. As you can see, the do statement executes before reading the while clause.

These are just a few ways to rewrite for loops, and it is helpful to have different techniques depending on how you want the code to run.

πŸ’– πŸ’ͺ πŸ™… 🚩
sfrasica
Steven Frasica

Posted on July 9, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related