Do While Loop


The JavaScript do...while loop is a control flow statement that creates a loop that executes a block of code at least once, and then repeatedly executes the block, or not, depending on a given boolean condition at the end of the block. This structure is ideal when you need to perform an action at least one time and then continue looping based on a condition.


Example 1: Basic Counter

// Initialize a counter variable
let i = 0;

do {
  // Print the value of i to the console
  console.log(`The value of i is: ${i}`);
  // Increment the counter
  i++;
} while (i < 5); // The loop continues as long as i is less than 5

Explanation

This code initializes a variable i to 0. The do...while loop then prints the current value of i and increments it. The condition i < 5 is checked after the first execution, and the loop continues until i is no longer less than 5.


Example 2: User Input Validation

let input;

do {
  // Prompt the user for input
  input = prompt("Please enter a number greater than 10:");
} while (isNaN(input) || input <= 10); // Continue prompting if the input is not a number or is not greater than 10

console.log("You entered a valid number:", input);

Explanation

This example demonstrates how to use a do...while loop for input validation. It will continuously prompt the user to enter a number until they provide a value that is a number and is greater than 10, ensuring valid input is received.


Example 3: Menu Selection

let choice;

do {
  // Display a menu and get the user's choice
  choice = prompt("Select an option:\n1. Start Game\n2. Options\n3. Exit");
} while (choice !== "3"); // Continue showing the menu until the user chooses to exit

console.log("Exiting the menu.");

Explanation

This code snippet showcases a simple menu system. The do...while loop ensures the menu is displayed at least once and will keep reappearing until the user enters "3" to exit the menu.


Example 4: Simulating a Dice Roll

let diceRoll;

do {
  // Generate a random number between 1 and 6
  diceRoll = Math.floor(Math.random() * 6) + 1;
  // Log the result of the roll
  console.log(`You rolled a ${diceRoll}`);
} while (diceRoll !== 6); // The loop continues until a 6 is rolled

console.log("You rolled a 6!");

Explanation

This example simulates rolling a die. The do...while loop guarantees the die is rolled at least once and continues to "roll" until the result is a 6.


Example 5: Countdown Timer

let count = 5;

do {
  // Display the current count
  console.log(`Countdown: ${count}`);
  // Decrement the count
  count--;
} while (count >= 0); // Continue counting down as long as the count is non-negative

console.log("Liftoff!");

Explanation

This code implements a simple countdown timer. The do...while loop starts at 5 and counts down to 0, printing each number along the way before finally printing "Liftoff!".


Example 6: Fetching Data Until Success

let dataFetched = false;
let attempts = 0;

do {
  attempts++;
  console.log(`Attempt ${attempts}: Fetching data...`);
  // In a real scenario, an actual data fetching operation would be here.
  // We'll simulate a potential failure and success.
  if (Math.random() > 0.5) {
    dataFetched = true;
    console.log("Data fetched successfully!");
  } else {
    console.log("Failed to fetch data, retrying...");
  }
} while (!dataFetched); // Continue trying to fetch data until it is successful

Explanation

This example simulates an attempt to fetch data that might fail. The do...while loop ensures the fetch operation is attempted at least once and will retry until the dataFetched variable becomes true.


Example 7: Array Manipulation

const numbers = [10, 20, 30, 40, 50];
let i = 0;

do {
  // Double the value of the current element in the array
  numbers[i] *= 2;
  // Move to the next index
  i++;
} while (i < numbers.length); // Continue as long as there are elements in the array

console.log("Modified array:", numbers); // Output will be [20, 40, 60, 80, 100]

Explanation

In this final example, we manipulate an array. The do...while loop iterates through the numbers array, doubling the value of each element.