Home ยป JavaScript do while Loop: A Complete Tutorial with Examples

JavaScript do while Loop: A Complete Tutorial with Examples

The do…while loop in JavaScript is similar to the while loop, with one key difference: a do…while loop will execute the code block at least once, even if the condition is false.

This is because the condition is evaluated after the code block is executed.

Syntax of the do…while Loop

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

Explanation

do: This block of code will run first before the condition is checked.
while (condition): The loop will continue to run as long as this condition is true.

1. Basic do…while Loop Example

Let's start with a simple example that prints numbers from 1 to 5.

let number = 1;

do {
  console.log(number);
  number++;
} while (number <= 5);

Output:

1
2
3
4
5

Explanation

The code inside the do block is executed first, so 1 is printed.
After the code block runs, the while condition (number <= 5) is checked.
If the condition is true, the loop runs again; otherwise, it stops.

2. Executing the Loop at Least Once

One of the main benefits of using a do…while loop is that the code block will always execute at least once, even if the condition is false to begin with.

let count = 10;

do {
  console.log(count);
  count++;
} while (count < 5);

Output:

10

Explanation

The loop executes the do block first, printing 10.
Then it checks the condition (count < 5), which is false.
Since the condition is false, the loop stops after the first execution.

3. do…while Loop for Input Validation

The do…while loop is handy for validating user input. Here's an example where the loop prompts the user for a number greater than 10:

let userInput;

do {
  userInput = parseInt(prompt('Enter a number greater than 10:'));
} while (userInput <= 10 || isNaN(userInput));

console.log(`You entered: ${userInput}`);

Explanation

The do block executes first, prompting the user to input a number.
The while condition checks if the input is less than or equal to 10 or is NaN.
The loop repeats until the user enters a valid number greater than 10.

Note: This example uses prompt() for input, which works in a browser environment.

4. Using break to Exit a do…while Loop

You can use the break statement inside a do…while loop to exit it prematurely based on a specific condition.

let i = 1;

do {
  console.log(i);
  if (i === 3) {
    break; // Exit the loop when i is 3
  }
  i++;
} while (i <= 5);

Output:

1
2
3

Explanation

The loop starts with i = 1 and prints numbers.
When i equals 3, the break statement exits the loop.
The loop stops even though the while condition is still true.

5. Using continue to Skip an Iteration

The continue statement can be used in a do…while loop to skip the current iteration and move to the next one.

let num = 0;

do {
  num++;
  if (num % 2 === 0) {
    continue; // Skip even numbers
  }
  console.log(num);
} while (num < 10);

Output:

1
3
5
7
9

Explanation

The loop increments num before checking the if condition.
If num is even (num % 2 === 0), the continue statement skips the rest of the loop's code and moves to the next iteration.
Only odd numbers are printed.

6. Nested do…while Loops

You can nest do…while loops to handle more complex scenarios, like printing a simple multiplication table.

let i = 1;

do {
  let j = 1;
  
  do {
    console.log(`${i} * ${j} = ${i * j}`);
    j++;
  } while (j <= 5);
  
  i++;
} while (i <= 5);

Output:

1 * 1 = 1
1 * 2 = 2
...
5 * 4 = 20
5 * 5 = 25

Explanation

The outer do…while loop iterates over i from 1 to 5.
For each iteration of i, the inner do…while loop iterates over j from 1 to 5.
This prints the multiplication table for numbers 1 through 5.

7. do…while Loop with Arrays

The do…while loop can be used to iterate through an array, especially if you need to process at least one element regardless of conditions.

let fruits = ['apple', 'banana', 'cherry'];
let index = 0;

do {
  console.log(fruits[index]);
  index++;
} while (index < fruits.length);

Output:

apple
banana
cherry

Explanation

The loop starts with index = 0.
It prints each element in the fruits array.
The loop continues until index is equal to the length of the array.

Conclusion

The do…while loop in JavaScript is useful when you need to guarantee that a block of code runs at least once, regardless of whether the condition is initially true or not.

Here are some key takeaways:

The code inside the do block executes before the condition is checked.
Always remember to modify the loop variable within the loop to avoid infinite loops.
Use break to exit the loop and continue to skip the current iteration when necessary.

By understanding how to use the do…while loop, you can handle situations where you need to ensure at least one iteration of code execution before checking a condition. Happy coding!

You may also like