The while instruction.

The while instruction is used in a program to implement what is called simple repetition. That means that you can use it if you wanted to carry out the same set of instructions many times over. Just say you wanted to calculate a deduction of 10% on all the items on sale in your shop and write the new price and the saving on each item. You might write a program like this:

price=promptNumber ("How much is the item?")

while (price !=0)
{
deduction=price * 0.1
saleprice=price - deduction
alert ("The sales price is £ " + saleprice
+ "and the deduction is £" + deduction)
price=promptNumber ("How much is the item?")
}

This program will repeatedly ask the user to type in prices, and will calculate the new sales prices until the user finally enters a price of zero.

Copy the program into the box below and try it out.

Looking at the program above, you should note the following:

  1. The while instruction spans several lines .
  2. After the word while there is a set of parentheses ( ) with a test in it. This particular test is checking to see if the variable price does not contain the number 0.
  3. If the test is true (i.e if price does not contain 0) then all the instructions between the set of braces { } will be executed.
  4. When this set of instructions has been completed it will check once more to see if the test in parentheses after the word while is still true and if it is it will carry out the set of instructions again.
  5. It will do this over and over again until eventually something happens to make the test false (NOT true)
  6. If the test is NOT true (i.e. if the contents of the variable price is greater or equal to 0) then the instructions between the set of braces will be ignored and the program will continue on with any instructions after the end brace }
  7. This is often called a while loop because the computer goes over the same instructions many times.

Question: Is it possible to get stuck in a while loop forever?
Answer:
Yes. If the test never becomes false the computer will keep repeating the set of instructions for as long as you keep the computer turned on..

Question: Why is the sequence of instructions surrounded by braces?
Answer:
So it is clear where the sequence of instructions starts and finishes.

Click on the Back button on the tool bar to return to where you were.

List of Javascript lectures Relevant JavaScript Practicals (17 - 19)