start learning
Image 1
48956

do-while loop

The "do-while loop" in JavaScript is a looping construct that is similar to the "while loop." It repeatedly executes a block of code as long as a specified condition remains true. The key difference between the "do-while loop" and the "while loop" is that the "do-while loop" guarantees that the code block will be executed at least once, even if the condition is initially false.

The basic syntax of a "do-while loop" in JavaScript is as follows:


do {
    // Code to execute
} while (condition);

Here's how the "do-while loop" works:

  1. The code block is executed first, regardless of the condition.
  2. After the code block is executed, the condition is evaluated.
  3. If the condition is true, the loop's block of code is executed again; otherwise, the loop terminates.
Example:

var i = 0;

do {
    console.log("Value of i: " + i);
    i++;
} while (i < 5);

In this example, the loop initializes i to 0, executes the code block (printing the value of i), increments i by 1, and then checks if i is less than 5. This process repeats until i is no longer less than 5.

The "do-while loop" is useful when you want to ensure that a certain task is executed at least once, regardless of the condition's initial state. Just like with other loops, be careful with your condition to prevent infinite loops.