javascript-bucle-while

What is and how to use the WHILE and DO-WHILE loop in JavaScript

  • 5 min

The while and do-while loops are control structures in JavaScript that allow repeating the execution of a block of code as long as a specific condition is met.

Unlike the for loop, which is used when the exact number of iterations is known, the while and do-while loops are ideal when the number of iterations is unknown or depends on an exit condition.

If you want to learn more, check out the Introduction to Programming Course

While loop

The while loop repeats a block of code as long as a given condition is true. The basic syntax of a while loop in JavaScript is as follows:

while (condition) {
    // Code to execute while the condition is true
}
Copied!

The block of code is executed repeatedly as long as the specified condition is true. It is important to be careful with the condition to avoid infinite loops.

Basic example

let counter = 0;

while (counter < 5) {
    console.log(counter);
    counter++;
}
Copied!

In this example, the while loop will print the numbers from 0 to 4, since the condition counter < 5 evaluates to true during the first five iterations.

Do-while loop

The do-while loop is similar to the while loop, but it guarantees that the block of code is executed at least once, even if the condition is false from the start. The basic syntax is as follows:

do {
    // Code to execute at least once
} while (condition);
Copied!

The block of code is executed first and then the condition is checked. If the condition is true, the block is executed again; if it is false, the loop ends.

Basic example

let counter = 0;

do {
    console.log(counter);
    counter++;
} while (counter < 5);
Copied!

This do-while loop will produce the same output as the while loop in the previous example.

Differences between while and do-while

  • The while loop checks the condition before each iteration, while the do-while loop checks the condition after each iteration.
  • The do-while loop guarantees at least one execution of the code block, while the while loop may not execute the block if the condition is false from the start.

Practical examples

These examples are intended to show how to use while and do-while loops. It does not mean that it is the best way to solve the problem they address.