DEV Community

Steven Frasica
Steven Frasica

Posted on


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



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 {



} 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.

Top comments (0)

11 Tips That Make You a Better Typescript Programmer


1 Think in {Set}

Type is an everyday concept to programmers, but it’s surprisingly difficult to define it succinctly. I find it helpful to use Set as a conceptual model instead.

#2 Understand declared type and narrowed type

One extremely powerful typescript feature is automatic type narrowing based on control flow. This means a variable has two types associated with it at any specific point of code location: a declaration type and a narrowed type.

#3 Use discriminated union instead of optional fields


Read the whole post now!