JavaScript > JavaScript Fundamentals > Control Structures > do...while loops

JavaScript do...while Loop: Number Guessing Game

This code snippet demonstrates the use of the do...while loop in JavaScript to create a simple number guessing game. The game prompts the user to guess a randomly generated number until they guess correctly.

The Goal

The goal of this snippet is to illustrate the fundamental use of the do...while loop to execute a block of code at least once, and then repeatedly based on a condition. In this case, the code runs until the user guesses the correct number.

Code Implementation

This code first generates a random number. Then, a do...while loop is used to repeatedly prompt the user to guess the number. The loop continues until the user's guess matches the random number. Input validation is included to ensure that the user enters a valid number.

// Generate a random number between 1 and 10
const randomNumber = Math.floor(Math.random() * 10) + 1;
let guess;
let attempts = 0;

do {
  guess = parseInt(prompt("Guess a number between 1 and 10:"));
  attempts++;

  if (isNaN(guess)) {
    alert("Invalid input. Please enter a number.");
    continue; // Skip to the next iteration
  }

  if (guess < randomNumber) {
    alert("Too low! Try again.");
  } else if (guess > randomNumber) {
    alert("Too high! Try again.");
  }
} while (guess !== randomNumber);

alert(`Congratulations! You guessed the number ${randomNumber} in ${attempts} attempts.`);

Concepts behind the snippet

The do...while loop is a control flow statement 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 is different from a regular while loop, which checks the condition before executing the block.

Real-Life Use Case Section

do...while loops are useful when you need to execute a block of code at least once, such as in scenarios where you need to get input from the user and validate it, or when you need to perform an action before checking if you need to repeat it. For example, reading data from a file and processing it until the end of the file is reached.

Best Practices

  • Always ensure that the loop condition will eventually evaluate to false to avoid infinite loops.
  • Use break or continue statements sparingly to control the flow of the loop.
  • Provide clear prompts and feedback to the user when using do...while loops for input validation.

Interview Tip

Be prepared to explain the difference between while and do...while loops. The key difference is that do...while loops always execute the code block at least once, regardless of the initial condition.

When to use them

Use a do...while loop when you need to ensure that a block of code is executed at least once, regardless of the initial condition. This is useful for tasks such as input validation, menu-driven programs, and any scenario where an initial action must be performed before checking the loop condition.

Memory footprint

The memory footprint of a do...while loop is generally small. It primarily consists of storing the loop condition and any variables used within the loop. The memory usage increases with complex logic or large data structures within the loop's code block.

Alternatives

Alternatives to do...while loops include while loops and for loops. The choice depends on the specific requirements of the task. If you don't need to execute the code block at least once, a while loop is often a better choice.

Pros

  • Guarantees execution of the code block at least once.
  • Simple syntax for repeating a block of code based on a condition.

Cons

  • Can be less readable than while loops in some cases, as the condition is checked at the end of the loop.
  • If the loop condition is always true, it can lead to an infinite loop.

FAQ

  • What is the main difference between a while loop and a do...while loop?

    The main difference is that a do...while loop executes the code block at least once, whereas a while loop may not execute the code block at all if the condition is initially false.
  • How can I prevent an infinite loop in a do...while loop?

    Ensure that the loop condition will eventually evaluate to false. This can be achieved by modifying variables within the loop that are used in the condition. Properly validating data that influences the loop is also important.