JavaScript – Exercise 10 : The While Loop

Just as the “for loop” repeated all the statements within the loop body, “while loop” also does the same thing. It is another type of loop that repeats everything inside the loop until the loop condition is false.


The typical structure of while loop is given below.

 n = 10;
 i = 0;

 while( i < n)

      statement 1;
      statement 2;
      statement n;

The working of the “While Loop” is easy to understand using an example program. So we are going to create a page that will make use of JavaScript and do some action with “While Loop”. We call this web page as “loop2.HTML”.

The JavaScript Code

The JavaScript code that we are going to use is as follows.

var i=0;

while(i<=5) {     

    document.write("<h3>" + "The Value of I is" + i + "</h3>");     

The while loop has the statement ‘The Value of I is + i’ which is repeated n times when the loop executes.

The HTML file – loop2.HTML

Now we give the code for HTML file that contains the above JavaScript code.

<!DOCTYPE html>
   <title>While Loop</title>
   <meta charset = "utf-8">
   var i=0;
   while(i<=5)  {    
     document.write( "<h3>" + "The Value of I is" + i + "</h3>" );                 
   <p>When you open this web page in a browser that understands the               JavaScript, then you will get the following output.</p>

The page when loaded to browser will produce the following output. If you do not get the correct output then your browser does not support JavaScript or there may be something wrong with your code.


Output - Ex 10 - While Loop
Output – Ex 10 – While Loop


Ads Blocker Image Powered by Code Help Pro

Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.