Home > DeveloperSection > Articles > The while loop in JavaScript

The while loop in JavaScript


JavaScript JavaScript 
Ratings:
0 Comment(s)
 2484  View(s)
Rate this:

The while loop in JavaScript

Introduction:

Loops are the basic parts and the most commonly used ones in programming languages. In Java Script also loop are used basically in this article I will explain while loop and do while loop constructs.

The while loop is one of the basic loop used in java script. It is there in all the language; in java script also it is there.

Syntax:

while (condition)

  {

  code to be executed  // if condition is true;

  }

It is used when we have to repeat a task for a certain number of times, till the condition is satisfied. So we do not have to write one code that is required several time.With the help of loop it will be repeated several times we want

For exampe

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

    <script type="text/javascript">

        function whileloop() {

            var i = 0;

            document.write("Loop Started.... " + "<br/>")

            while (i < 10) {

                document.write("value of i is " + i + "<br/>")

                i++;

            }

            document.write("Loop Stopped. " + "<br/>")

        }

    </script>

</head>

<body>

    <div>

        <input id="btnStart" type="button" value="Start" onclick="whileloop();" />

    </div>

</body>

</html>

 

Output:

The while loop in JavaScript

 Do While Loop:

There is a very small difference between while loop and a do while loop. In a do while loop, block of code will be executed once before checking whether the condition is true or false. The do while loop will be executed one time even if the condition is false.

Syntax of do while loop:

do {

//code to be executed   //   One time it will execute even if the condition is false

}  while(condition);

Example depicting the use of do while loop in Java Script:

 

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

    <script type="text/javascript">

        function dowhile() {

            var j = 0;

            document.write("Loop Started..." + "<br/>")

            do {

                document.write("Value of j is: " + j + "<br/>");

                j++;

            } while (j < 0);

            document.write("Loop Stopped.");

        }

    </script>

</head>

<body>

    <div>

        <input id="btnStart" type="button" value="start" onclick="dowhile();" />

    </div>

</body>

</html>

 

Output:

The while loop in JavaScript

 

We can see in the example that the condition is checked after the first time the statement in the loop is executed.

Conclusion:

In this article I tried to explain the concept of both while and do while loops both the loops are important and are used in Java Script so understanding the working of these will make programming easier.


Don't want to miss updates? Please click the below button!

Follow MindStick