Javascript While loop vs. Do while loop

You are currently viewing Javascript While loop vs. Do while loop

Javascript While loop vs. Do while loop

In JavaScript, both while and do-while loops are used to execute a block of code repeatedly. The main difference between them is that the while loop tests the condition before executing the block of code, whereas the do-while loop executes the block of code at least once before testing the condition. There is a key difference in how they check the condition and execute the loop:

In JavaScript, both while and do-while loops are used to execute a block of code repeatedly. The main difference between them is that the while loop tests the condition before executing the block of code, whereas the do-while loop executes the block of code at least once before testing the condition. There is a key difference in how they check the condition and execute the loop:

1) While Loop

  • In a while loop, the condition is checked before the loop body is executed.
  • If the condition is initially false, the loop body will not execute at all.
  • If the condition becomes false during the loop execution, the loop will terminate, and the loop body will not execute for subsequent iterations.
    Here’s the syntax of a while loop:
				
					while (condition) {
  // // code to be executed as long as the condition is true
}

				
			

JavaScript while Loop: Example

				
					<html>
<body data-rsssl=1>
<script>
var i = 1;
           
while (i <= 5)
{
document.write(" The number is "+ i +"<br/>");
i++;
}
</script> 
      
</body>
</html>

				
			
				
					Output :
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5

				
			

2) Do-While Loop

  • In a do-while loop, the loop body is executed at least once, regardless of whether the condition is true or false.
  • After the loop body executes, the condition is checked.
  • If the condition is true, the loop continues to execute; otherwise, it terminates.
    Here’s the syntax of a do-while loop:
				
					do {
  // code to be executed at least once
} while (condition);

				
			

JavaScript do..while Loop: Example

				
					<html>
 <body data-rsssl=1>
<script>
var i = 1;
           
do 
{
document.write(" The number is "+ i +"<br/>");
i++;
}
while(i <= 5)
</script> 
       
 </body>
</html>


				
			
				
					Output :
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5

				
			

This code will also print the numbers from 1 to 5, but it guarantees that the loop body is executed at least once, even if the condition is initially false.

Leave a Reply