- Previous
- Next
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;
i++;
}
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>");
i++;
}
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>
<html>
<head>
<title>While Loop</title>
<meta charset = "utf-8">
</head>
<body>
<script>
var i=0;
while(i<=5) {
document.write( "<h3>" + "The Value of I is" + i + "</h3>" );
i++;
}
</script>
<p>THIS IS TEST USING INTERNAL JAVA SCRIPT</p>
<p>When you open this web page in a browser that understands the JavaScript, then you will get the following output.</p>
</body>
</html>
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.