Open In App
Related Articles

JavaScript While Loop

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

A While Loop in JavaScript is a control flow statement that allows the code to be executed repeatedly based on the given boolean condition. The while loop can be thought of as a repeating if statement. The loop can be used to execute the specific block of code multiple times until it fails to match the condition.

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:

while (condition) {
// Statements
}

Example: This example illustrates the use of a while loop.

JavaScript

// JavaScript code to use while loop
let val = 1;
while (val < 6) {
    console.log(val); 
    val += 1;
}

                    

Output
1
2
3
4
5

Do-While loop

A do-while loop is a control flow statement that executes a block of code at least once, and then repeatedly executes the block or not depending on a given boolean condition at the end of the block.

Syntax:

do {
// Statements
}
while (condition);

Example: This example illustrates the use of the do-while loop.

JavaScript

// JavaScript code to use while loop
let val = 1;
do {
    console.log(val);
 
    val += 1;
 
} while (val < 6);

                    

Output
1
2
3
4
5

Comparison between the while and the do-while loop: The do-while loop executes the content of the loop once before checking the condition of the while loop. While the while loop will check the condition first before executing the content.

While Loop

Do-While Loop

It is an entry condition looping structure.

It is an exit condition looping structure.

The number of iterations depends on the condition mentioned in the while block.

Irrespective of the condition mentioned in the do-while block, there will a minimum of 1 iteration.

The block control condition is available at the starting point of the loop.

The block control condition is available at the endpoint of the loop.

We have a Cheat Sheet on JavaScript where we covered all the important topics of JavaScript to check those please go through JavaScript Cheat Sheet – A Basic Guide to JavaScript.



Last Updated : 22 Dec, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads