JavaScript From Beginner To Advanced

0% completed

Previous
Next
JavaScript - do-while loop

The do-while loop is a control flow statement that allows a section of code to be executed at least once before a condition is checked. Unlike the while loop, which tests the condition before the first iteration, the do-while loop ensures the code inside the loop runs once even if the condition is false from the start. This feature is particularly useful in scenarios where an initial execution is required regardless of the condition's outcome.

Understanding the do-while Loop

In programming, certain operations need to be executed at least once and then repeated based on a specific condition. The do-while loop is tailor-made for such situations, providing a clear and concise way to implement this logic.

Syntax

Here's the basic syntax of a do-while loop in JavaScript:

Image
Javascript
Javascript
. . . .
  • The code block inside the do statement executes once unconditionally.
  • After the execution, the condition is evaluated.
  • If the condition is true, the loop runs again. This repeats until the condition becomes false.

Execution Flow

The execution flow of the do-while loop is as shown in flow-chart below.

Image

Examples

Let's explore three simple yet illustrative examples of using do-while loops, complete with brief comments for clarity.

Example 1: Counter

A basic usage of the do-while loop is to implement a counter that increments from 1 to 5.

Javascript
Javascript

. . . .

In this example, the loop prints numbers 1 through 5 to the console. The loop ensures the first print operation occurs, then checks if the count is less than or equal to 5 to decide whether to continue.

Example 2: Random Number Until Five

Generate random numbers between 1 and 10 until the number 5 is generated.

Javascript
Javascript

. . . .

Here, the loop continues to generate and print a random number until it produces the number 5. It showcases a scenario where you don't know how many iterations are needed, but at least one execution is guaranteed.

The do-while loop in JavaScript is a powerful tool for situations requiring at least one execution of a block of code, with subsequent iterations dependent on a specific condition. Through the examples provided, you can see how the do-while loop is applicable in various scenarios, from simple counting to conditional operations based on user input or random events. Understanding how and when to use this loop enhances your ability to write efficient and effective JavaScript code.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next