search ]

Understanding the JavaScript do-while Loop: Syntax and Examples

Loops are an essential programming construct that allows you to execute a specific piece of code multiple times until a given condition is met. Instead of writing repetitive code, loops enable you to efficiently run a set of instructions for as many times as necessary.

In this post, we’ll focus on the do-while loop in JavaScript, explaining its syntax and usage with practical examples.

The do-while loop is particularly useful when you need to ensure that a block of code runs at least once, regardless of the condition.

The do-while Loop in JavaScript

Unlike the for or while loops, the do-while loop always executes the block of code once before checking the condition. This is because the condition is evaluated after the loop body has executed. Here’s the basic syntax of the do-while loop in JavaScript:

do {
  statement;
} while (condition);

Here’s a breakdown of what happens behind the scenes:

  1. The statement (loop body) is executed.
  2. After the statement is executed, the condition is evaluated. If the condition evaluates to true, the loop continues and the statement runs again. If the condition evaluates to false, the loop terminates.

In contrast to the for and while loops, the do-while loop guarantees that the loop body executes at least once, regardless of the condition.

Example A: Display a Message 5 Times

In this example, we use a do-while loop to display a message 5 times:

// program to display a message 5 times
let i = 1;
const n = 5;

do {
    console.log('I love JavaScript.');
    i++;
} while (i <= n);

Output:

I love JavaScript.
I love JavaScript.
I love JavaScript.
I love JavaScript.
I love JavaScript.

In this case, the loop runs 5 times, as the value of i is incremented after each iteration and checked against the value of n.

Example B: Displaying Numbers from 1 to 5

Here, we use a do-while loop to print numbers from 1 to 5:

// program to display numbers from 1 to 5
let i = 1;
const n = 5;

do {
    console.log(i);
    i++;
} while (i <= n);

Output:

1
2
3
4
5

In this example, the loop runs as long as i <= 5. Even if the initial value of i had been greater than 5, the loop would still run once before checking the condition.

Key Differences Between <code>while</code> and <code>do-while</code> Loops

The main difference between the while and do-while loops lies in when the condition is checked:

  • while loop: The condition is checked at the beginning, before the loop body executes. If the condition is false initially, the loop body will not run.
  • do-while loop: The loop body executes first, and the condition is checked afterward. This ensures that the loop body runs at least once, even if the condition is initially false.

Here’s an example that demonstrates the difference between the two loops:

Using a while Loop:

let i = 6;
const n = 5;

while (i <= n) {
    console.log(i);
    i++;
}

Output: (Nothing will be printed since the condition is false initially.)

Using a do-while Loop:

let i = 6;
const n = 5;

do {
    console.log(i);
    i++;
} while (i <= n);

Output:

6

In this case, even though the condition is initially false, the do-while loop executes the loop body at least once, which is why the number 6 is printed.

Example C: Sum of Natural Numbers from 1 to 100

Let’s use the do-while loop to calculate the sum of natural numbers from 1 to 100:

// program to display the sum of natural numbers
let sum = 0;
let i = 1;
const n = 100;

do {
    sum += i;
    i++;
} while (i <= n);

console.log('Sum:', sum);

Output:

Sum: 5050

This loop adds the value of i to the sum variable and continues to do so until i reaches 101, at which point the condition fails and the loop stops.

Example D: Using do-while to Validate User Input

The do-while loop is often useful in scenarios where you need to validate user input and ensure that the loop runs at least once before performing the validation.

let number;

do {
    number = prompt("Enter a number greater than 10:");
} while (number <= 10);

console.log("You entered: " + number);

In this example, the loop prompts the user for input and continues to ask for a number until a value greater than 10 is entered.

Conclusion

The do-while loop in JavaScript is a versatile construct that guarantees at least one execution of the loop body, making it particularly useful for tasks where the condition must be evaluated after running the code. While similar to the while loop, the do-while loop stands out due to its unique structure and behavior.

Understanding the do-while loop, along with other loop types, is critical for efficient coding in JavaScript. If you want to explore more about loops, check out my post on the JavaScript for loop, where I dive into a similar yet distinct loop structure.

Roee Yossef
Roee Yossef

I develop pixel-perfect custom WordPress themes, delivering high-performance, SEO-optimized websites. Have a project in mind? need assistance? Feel free to contact me!

0 Comments...

Leave a Comment

To add code, use the buttons below. For instance, click the PHP button to insert PHP code within the shortcode. If you notice any typos, please let us know!