Home » Online Computer Education » Learn Java Script, The while Statement, Lesson No. 23

Learn Java Script, The while Statement, Lesson No. 23

 

 

The while statement executes a loop as long as a condition is true. The syntax of the while statement is shown here:

while (condition) {
statements;
}
For example, you might write a while loop that looks like this:

while (counter > 0) {
counter++;
document.write(“counter = “, counter , “<BR>”);
}
In the next example, I set up a loop that runs as long as the value assigned to a variable named counter is greater than 0. As soon as counter becomes 0 or less, the loop terminates. To control the termination of the loop, I decremented the value of counter by 1 each time through the loop. When working with while loops, be sure that you set them up so that they will properly break out of the loop; otherwise, they will run forever, leaving the user no option other than to close the HTML page or terminate the execution of your JScript.

This is because the while loop is designed to iterate for as long as the tested condition remains true, as demonstrated in the following example.

<HTML>
<HEAD>
<TITLE>Script 2.13 – Demonstration of the while
statement</TITLE>
</HEAD>
<BODY>
<SCRIPT LANGUAGE=”JavaScript” TYPE=”Text/JavaScript”>
<!– Start hiding JavaScript statements

var counter = 10;

document.write(“<B>Watch me count backwards!</B><BR>”);

while (counter > 0) {
counter;
document.write(“counter = “, counter , “<BR>”);
}

// End hiding JavaScript statements –>
</SCRIPT>
</BODY>
</HTML>
shows the results of loading this example using Internet Explorer.

An example of looping backward using a while loop

9

About

The main objective of this website is to provide quality study material to all students (from 1st to 12th class of any board) irrespective of their background as our motto is “Education for Everyone”. It is also a very good platform for teachers who want to share their valuable knowledge.

Leave a Reply

Your email address will not be published. Required fields are marked *