JavaScript while and do...while


In JavaScript, loops are a core concept for repeating code. While the for loop is often used for a known number of iterations, the while loop and do...while loop are powerful tools when the number of iterations is determined by a condition rather than a fixed count. Both loops execute a block of code as long as a specified condition remains true. However, there are key differences in how they evaluate the condition.


1. What is a while Loop in JavaScript?

A while loop executes a block of code as long as a specified condition evaluates to true. The condition is checked before each iteration, meaning the loop may not run at all if the condition is false initially.

Syntax of the while Loop:

while (condition) {
  // Code to be executed as long as the condition is true
}
  • Condition: This is evaluated before each iteration. If it is true, the loop continues; if false, the loop terminates.

Example 1: Basic while Loop

let i = 0;

while (i < 5) {
  console.log("Iteration number: " + i);
  i++;  // Incrementing the counter
}

Explanation:

  • The loop will run as long as i is less than 5.
  • The condition (i < 5) is evaluated before each iteration.
  • The value of i is incremented inside the loop, ensuring the loop progresses towards termination.
  • The output will be:
    Iteration number: 0
    Iteration number: 1
    Iteration number: 2
    Iteration number: 3
    Iteration number: 4
    

2. What is a do...while Loop in JavaScript?

The do...while loop is similar to the while loop, but with a key difference: the condition is evaluated after each iteration. This guarantees that the code inside the loop is executed at least once, even if the condition is false from the start.

Syntax of the do...while Loop:

do {
  // Code to be executed
} while (condition);
  • Code Block: This block of code runs at least once, and then the condition is checked.
  • Condition: The condition is evaluated after each iteration. If true, the loop runs again.

Example 2: Basic do...while Loop

let i = 0;

do {
  console.log("Iteration number: " + i);
  i++;  // Incrementing the counter
} while (i < 5);

Explanation:

  • The loop runs the code block first and then checks the condition (i < 5).
  • The value of i is incremented after each iteration.
  • The output will be:
    Iteration number: 0
    Iteration number: 1
    Iteration number: 2
    Iteration number: 3
    Iteration number: 4
    

3. Key Differences Between while and do...while Loops

Although both loops are used for iteration, they have distinct behavior due to the timing of the condition check.

Aspect while Loop do...while Loop
Condition Check Condition is checked before each iteration. Condition is checked after each iteration.
Execution Guarantee Code may not execute if the condition is false initially. Code always executes at least once, even if the condition is false.
Usage Ideal when you are not sure how many iterations are needed, and the condition should be checked first. Useful when the loop should run at least once, regardless of the condition.

4. Practical Use Cases of while and do...while Loops

Example 3: Using a while Loop for User Input Validation

Imagine you want to repeatedly ask the user for input until they provide a valid response. This is a perfect scenario for a while loop.

let userInput = "";
while (userInput !== "yes") {
  userInput = prompt("Do you want to continue? (yes/no)");
}
console.log("User agreed to continue!");

Explanation:

  • The loop will continue asking for input as long as the user’s input is not "yes".
  • The condition is checked before each iteration to ensure the user has answered correctly.

Example 4: Using a do...while Loop for Menu Options

A do...while loop can be handy when displaying a menu and prompting users for their selection at least once.

let userChoice;
do {
  userChoice = prompt("Choose an option:\n1. Option A\n2. Option B\n3. Exit");
  switch(userChoice) {
    case "1":
      console.log("You chose Option A");
      break;
    case "2":
      console.log("You chose Option B");
      break;
    case "3":
      console.log("Exiting...");
      break;
    default:
      console.log("Invalid choice, please try again.");
  }
} while (userChoice !== "3");

Explanation:

  • The do...while loop ensures the user sees the menu and is prompted at least once.
  • The loop will continue until the user chooses the "Exit" option.

5. Nested while and do...while Loops

You can also nest a while or do...while loop inside another loop to handle more complex scenarios, such as working with multi-dimensional arrays or more intricate conditions.

Example 5: Nested while Loop

let i = 1;
while (i <= 3) {
  let j = 1;
  while (j <= 3) {
    console.log("i = " + i + ", j = " + j);
    j++;
  }
  i++;
}

Explanation:

  • The outer while loop runs for i = 1 to i = 3.
  • The inner while loop runs for j = 1 to j = 3 for each iteration of the outer loop.
  • The output will be:
    i = 1, j = 1
    i = 1, j = 2
    i = 1, j = 3
    i = 2, j = 1
    i = 2, j = 2
    i = 2, j = 3
    i = 3, j = 1
    i = 3, j = 2
    i = 3, j = 3
    

6. Conclusion

Both the while loop and the do...while loop are important tools in JavaScript for repeating tasks under certain conditions. Understanding their differences and appropriate use cases will help you choose the right loop for your specific task.

Here’s a recap of the key points:

  • The while loop evaluates the condition before each iteration, which means the code inside the loop may not execute if the condition is false initially.
  • The do...while loop guarantees that the code runs at least once, checking the condition only after each iteration.
  • Both loops are highly flexible and can be used for a variety of tasks, including validating user input, displaying menus, and iterating over data.

By mastering both loops, you will be able to efficiently handle repetitive tasks in JavaScript.