While Loop In JavaScript

avatar

image.png

Image Source

While loop is one of many types of loop in JavaScript. For anyone new to programming, looping means repeatedly executing the same code by specifying a condition. When the condition becomes false, then the loop is terminated. This kind of loop is best used when you don't know how much iteration you want to perform in advance. The while loop in JavaScript has the following syntax:

while (condition)
{
 //statement
}

First the condition written inside the parenthesis is checked and is converted to a Boolean type i.e. true or false. If it is evaluated to false then the loop won't even run. If it is evaluated to true, then it enters the loop and executes the body inside the loop and after executing the statement, it returns to the beginning of loop and again evaluate the condition. It will continue on until the condition becomes false. Here we will see a simple code that prints first ten natural number using while loop in JavaScript.

<!DOCTYPE html>
<html lang="en">
<head>
<title>JavaScript While Loop</title>
<script>
    var i=0;
    while (i<=10)
    {
        document.write("<h4>"+"The Value of i is: " + i +"</h4>");
        i = i+1;
    }
</script>
</head>
<body>
</body>
</html>

If you see the output in the browser, the following will be shown:

image.png



0
0
0.000
2 comments