A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/javascript/javascript-do-while-loop/ below:

JavaScript do...while Loop - GeeksforGeeks

JavaScript do...while Loop

Last Updated : 30 Jul, 2024

A do...while loop in JavaScript is a control structure where the code executes repeatedly based on a given boolean condition. It's similar to a repeating if statement. One key difference is that a do...while loop guarantees that the code block will execute at least once, regardless of whether the condition is met initially or not.

There are mainly two types of loops.

Syntax:

do {
    // Statements
}
while(conditions)

Example 1: In this example, we will illustrate the use of a do...while loop

JavaScript
let test = 1;
do {
    console.log(test);
    test++;
} while(test<=5)

Output:

1
2
3
4
5

The main difference between do...while and while loop is that it is guaranteed that do...while loop will run at least once. Whereas, the while loop will not run even once if the given condition is not satisfied

Example 2: In this example, we will try to understand the difference between the two loops

JavaScript
let test = 1;
do {
    console.log(test);
} while(test<1)

while(test<1){
    console.log(test);
}

Output:

1

Explanation: We can see that even if the condition is not satisfied in the do...while loop the code still runs once, but in the case of while loop, first the condition is checked before entering into the loop. Since the condition does not match therefore the while loop is not executed.

Let us compare the while and do...while loop do...while while It is an exit-controlled loop It is an entry-controlled loop. The number of iterations will be at least one irrespective of the condition The number of iterations depends upon the condition specified The block code is controlled at the end   The block of code is controlled at starting

Note: When we are writing conditions for the loop we should always add a code that terminates the code execution otherwise the loop will always be true and the browser will crash.

Supported Browser:

We prefer you to check this article to know more about JavaScript Loop Statements.



RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4