Loading, please wait...

While Loop

While Loop

In JavaScript, while loop is used to execute a block of code in a number of times as long as the specified condition is true. Here, the condition is checked every time at the beginning of the loop.

 

Syntax

While (condition)
{
  Block of code
}

 

Code:

<html>
<body>
<h2>The While Loop</h2>
<script>
var x =1;
while(x<=5)
{
document.write(x + "<br>");
x++;
}
</script>
</body>
</html>

In the above example, the first part is that the value of x is initialized as 1.

The second part is the condition in a while loop for that the program executes until the condition is not false like the value of x is 1 and block of code of while loop is executed until when the condition is not false means when the value is 6.

 

Output: