The Wayback Machine - https://web.archive.org/web/20240930225136/https://www.geeksforgeeks.org/javascript-do-while-loop/
Open In App

JavaScript do…while Loop

Last Updated : 30 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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.

  • Entry Controlled loops: In this type of loop, the test condition is tested before entering the loop body. For Loop and While Loops are entry-controlled loops.
  • Exit Controlled Loops: In this type of loop the test condition is tested or evaluated at the end of the loop body. Therefore, the loop body will execute at least once, irrespective of whether the test condition is true or false. the do-while loop is exit controlled loop.

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…whilewhile
It is an exit-controlled loopIt is an entry-controlled loop.
The number of iterations will be at least one irrespective of the conditionThe 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:

  • Chrome
  • Edge
  • Safari
  • Firefox
  • Internet Explorer

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

JavaScript do…while Loop – FAQs

What is a do…while loop in JavaScript?

A do…while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. Unlike a regular while loop, a do…while loop will execute the code block once before checking the condition.

What is the basic syntax of a do…while loop?

The basic syntax of a do…while loop includes the do keyword followed by a code block in curly braces and the while keyword followed by a condition in parentheses.

How does the do…while loop work?

The do…while loop first executes the code block once, and then evaluates the condition. If the condition is true, the loop repeats, executing the code block again. This process continues until the condition evaluates to false.

What is the difference between while and do…while loops?

  • while loop: Checks the condition before executing the code block. If the condition is false initially, the code block may never execute.
  • do…while loop: Executes the code block once before checking the condition. This guarantees that the code block will execute at least once, even if the condition is false initially.

How do you break out of a do…while loop early?

You can use the break statement to exit a do…while loop before it completes all its iterations. This is useful if you want to stop the loop based on a condition inside the loop body.

How do you skip an iteration in a do…while loop?

You can use the continue statement to skip the current iteration and proceed to the next iteration of the loop. This is useful if you want to skip certain iterations based on a condition.


Previous Article
Next Article

Similar Reads

Difference between while and do-while loop in C, C++, Java
while loop: A while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The while loop can be thought of as a repeating if statement. Syntax : while (boolean condition){ loop statements...}Flowchart: Example: [GFGTABS] C++ #include <iostream> using namespace std; int main() { int i =
2 min read
How to Create a While Loop in JavaScript ?
In JavaScript, you can create a while loop using the while keyword followed by a condition. The loop continues to execute as long as the specified condition evaluates to true. Syntax:while (condition) { // Code to be executed while the condition is true // The condition is checked before each iteration}Example: Here, the loop continues to execute a
1 min read
How to Write a While Loop in JavaScript ?
In JavaScript, a while loop is a control flow statement that repeatedly executes a block of code as long as a specified condition is true. Syntax:while (condition) { // code block to be executed while condition is true}The loop continues to execute the block of code within its curly braces ({}) as long as the specified condition evaluates to true.
1 min read
JavaScript While Loop
The while loop executes a block of code as long as a specified condition is true. In JavaScript, this loop evaluates the condition before each iteration and continues running as long as the condition remains true. The loop terminates when the condition becomes false, enabling dynamic and repeated operations based on changing conditions. Syntax whil
3 min read
Difference between for and do-while loop in C, C++, Java
for loop: for loop provides a concise way of writing the loop structure. Unlike a while loop, a for statement consumes the initialization, condition and increment/decrement in one line thereby providing a shorter, easy to debug structure of looping. Syntax: for (initialization condition; testing condition; increment/decrement) { statement(s) } Flow
2 min read
Difference between for and while loop in C, C++, Java
In C, C++, and Java, both for loop and while loop is used to repetitively execute a set of statements a specific number of times. However, there are differences in their declaration and control flow. Let's understand the basic differences between a for loop and a while loop. for Loop A for loop provides a concise way of writing the loop structure.
5 min read
PHP while Loop
The while loop is the simple loop that executes nested statements repeatedly while the expression value is true. The expression is checked every time at the beginning of the loop, and if the expression evaluates to true then the loop is executed otherwise loop is terminated. Flowchart of While Loop: Syntax: while (if the condition is true) { // Cod
1 min read
PHP do-while Loop
The do-while loop is very similar to the while loop, the only difference is that the do-while loop checks the expression (condition) at the end of each iteration. In a do-while loop, the loop is executed at least once when the given expression is "false". The first iteration of the loop is executed without checking the condition. Flowchart of the d
1 min read
While loop with Compile time constants
While loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The while loop can be thought of as a repeating if statement. It is mostly used in situations where the exact number of iterations beforehand. Below is the image to illustrate the while loop: Syntax: while(test_expression){ // state
6 min read
How to loop through HTML elements without using forEach() loop in JavaScript ?
In this article, we will learn how to loop through HTML elements without using the forEach() method. This can be done in the following ways: Table of Content Approach 1: Using the for loopApproach 2: Using the While loopApproach 3: Using the 'for.....of' statementApproach 4: Using the for...in statementApproach 1: Using the for loopThe HTML element
4 min read
How to Loop Through an Array using a foreach Loop in PHP?
Given an array (indexed or associative), the task is to loop through the array using foreach loop. The foreach loop iterates through each array element and performs the operations. PHP foreach LoopThe foreach loop iterates over each key/value pair in an array. This loop is mainly useful for iterating through associative arrays where you need both t
2 min read
What’s the difference between “Array()” and “[]” while declaring a JavaScript array?
Consider the below codes: var myArray = new Array(5); and var myArray = [5]; Though these two lines might appear the same, but it is not the case. Consider the below explanations: Case 1: var myArray = new Array(5) This method is used to define an array of length 5. The parameter passed here '5' is an argument that defines the initial length of the
2 min read
How to solve the issue that arise while using performance.now() method in javaScript?
Any coder, given enough time, can solve a problem, the only thing matters are. Performance plays a very important role in software. A website with good performance can attract more number of users whereas the one with comparatively lesser or poor performance is not able to do so. As the use of JavaScript is increasing day by day in making very larg
5 min read
Validation of file size while uploading using JavaScript / jQuery
Validating the file size before uploading is an important step in enhancing user experience on a website. It helps prevent large files from being uploaded, which could lead to slow uploads, server overload, or bandwidth issues. Why File Size Validation is ImportantImproves User Experience: Prevents users from uploading files that are too large, sav
3 min read
File Type Validation while Uploading it using JavaScript
File type validation is essential for web applications that allow users to upload files. By checking the file extension on the client side using JavaScript, you can provide a smooth and efficient user experience by quickly notifying users if their file isn't supported. This method is often preferred over server-side validation because it reduces se
3 min read
How to change opacity while scrolling the page?
jQuery is used to control and change the opacity during the scrolling of web page. Create a web pages to change the opacity while scrolling the page. The jQuery scroll function is used to scroll the web page and set opacity of text content. Example: C/C++ Code <!-- HTML code to change the opacity of web page when scrolling it --> <!DOCTYPE
2 min read
How to trigger onchange event on input type=range while dragging in Firefox ?
Onchange: Onchange executes a JavaScript when a user changes the state of a select element. This attribute occurs only when the element becomes unfocused. Syntax: <select onchange="function()"> Attribute Value: It works on <select> element and fires the given JavaScript after the value is committed. Example: <!DOCTYPE html> <ht
2 min read
How to validate input field while focusout ?
The focusout() method in jQuery is used to remove the focus from the selected element. Now we will use focusout() method to validate the input field while focussing out. This method checks whether the input field is empty or not. Also, use some CSS property to display input field validation. If the input field is empty then it will display the red
2 min read
How to change Input characters to Upper Case while typing using CSS/jQuery ?
Given an input text area and the task is to transform the lowercase characters into uppercase characters while taking input from user. It can be done using CSS or JavaScript. The first approach uses CSS transform property and the second approach uses JavaScript to convert the lowercase character to upper case character. Approach 1: This approach us
2 min read
Why <big> tag is not in HTML5 while <small> tag exists ?
The <big> tag was discontinued in HTML5 while <small> tag is still in handy because <small> tag is frequently used to represent small prints like footnotes, copyright notices, comments etc. Many alternatives for <big> tag are already available such as <h1>, <h2> and so on. In HTML5 instead of using <big>, y
2 min read
SASS @for and @while Rule
@for rule is used to count up or down from one number to another and check the section for every number that comes in between the given range. Every number is assigned a given variable name. In order to exclude the last number, use to and in order to include it, use through. Syntax: @for <variable> from <expression> to <expression
2 min read
How to auto suggest rich contents while searching in Google AMP ?
Most of the auto-suggestions in sites would be normal strings but sometimes users look for more that, s, where this becomes useful rich content auto-suggestions, provide more information and clarity. Google AMP makes it easier for developers to use this option using amp-autocomplete. Required Scripts: Importing the amp-autocomplete component. <s
3 min read
How to create 2 column layout while keeping column background colors full size ?
In this article, we will learn how to make two-column layouts while keeping column background colors full size. Approach: We can make a two-column layout with background colors occupying full size by using the flexbox technique in CSS and by setting the height of the columns with respect to the viewport. HTML code: The following code demonstrates t
1 min read
How to hide credential information form URL while submitting the HTML Form?
In this article, we are going to learn how to hide the credential information in the URL while submitting the HTML Form. POST method is used for hiding the credential information. It gets the data from the fields of the HTML form and submits it via the HTTP header without being displayed in the URL. Suppose, If a user enters the credentials as user
2 min read
Handling Promise rejection with catch while using await
In this article, we will try to understand how we may handle Promise's rejection with a try/catch block while using await inside an asynchronous (having prefix as an async keyword) function (or a method). Syntax: Let us first quickly visualize the following illustrated syntax which we may use to create a Promise in JavaScript: let new_promise = new
2 min read
How to implement SSL Certificate Pinning while using React Native ?
In this article, we will be learning how to secure your react-native application by implementing SSL certificate pinning. Prerequisites: Basic knowledge of react native.The latest version of Node js and Android studio.Java SE Development Kit (JDK). A minimum of Java 8 Approach: The first question that will come into your mind would be why we need S
5 min read
Maintaining Aspect Ratio while Resizing Images in Web Development
When we are working with images in web development, it is a common need for developers to resize the image while keeping its aspect ratio fixed. This can be obtained by using CSS (Cascading Style Sheets). To know more about image tags, please refer to this article: https://www.geeksforgeeks.org/html-img-tag/ There are many ways to resize the image
3 min read
No 'Access-Control-Allow-Origin' header is present on the requested resource Error, while Postman does not?
When a client from one domain tries to send a request for a resource hosted in another domain, the "Access-Control-Allow-Origin header is not present on the requested resource" error is frequently seen. This happens due to the "Same-Origin Policy" which is a web browser security feature that stops malicious scripts from unauthorized accessing resou
4 min read
How to Hide the VueJS Syntax While the Page is Loading ?
Vue.js is a JavaScript framework used in building powerful and elegant user interfaces. In this article, we will learn how to hide the VueJS syntax while the page is loading. This approach ensures that users don't see the uncompiled Vue.js syntax during the initial page load, providing a smoother user experience. The following approaches can be use
3 min read
How to Narrow a Type of Derived Class Instances while Processing an Array ?
When it comes to JavaScript arrays that contain derived class instances, narrowing down the types is a must to access the specific functions or properties that are unique to those derived classes. Narrowing encompasses an act of specifically type-checking and casting objects explicitly to their derived types. Table of Content Using instanceof Opera
2 min read