Home » JavaScript » JavaScript While Loop

JavaScript While Loop Statement

In JavaScript while loop the condition is tested and if it evaluates to true only then, the control enters the loop and the block of code will get executed. After that, again the condition will be tested and if it again evaluates to true then again the code will be executed. This block will continue to execute as long as the condition is true. If at any time it evaluates to false, the loop execution will stop.

Syntax
while (condition is true)
{
// code to be executed
}


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title> JavaScript While Loop Statement </title>
</head>
<body>
<script>
var i=10;
while (i<=15)
{
document.write(i + "<br/>");
i++;
}
</script>
</body>
</html>

Output

JavaScript While Loop Statement

Note: The given condition should be false at sometime, Otherwise, the loop will never stop iterating which is known as infinite loop.

Here is the another example of While Loop


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title> JavaScript While Loop </title>
</head>
<body>
<p id="C0"></p>
<p id="C1"></p>
<p id="C2"></p>
<p id="C3"></p>
<p id="C4"></p>
<script>
var i =0;
while(i < 5)
{
document.getElementById("C" + i).innerHTML = i;
i++;
}
</script>
</body>
</html>

Output

JavaScript While Loop


Infinite loop

An infinite loop, is a loop that will keep running forever i.e. the condition specified in this loop will never evaluate to false. It can crash the browser or can hang the computer. People should be aware when writing the code that they shouldn't accidentally create an infinite loop.

Example- If there is 'i=2', and in while loop the condition is 'i>1', and inside the loop there is an increment in the value of 'i', then it will create an infinite loop as the value of 'i' will always be greater than '1' and hence the condition will be true always.

Example

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title> JavaScript While Loop Statement </title>
</head>
<body>
<script>
for (var i=0; i<Infinity; i++) {}
</script>
</body>
</html>











Follow Us: