JavaScript Tutorial Part 17: While and Do Loops

While Loops

Instead of using a for loop, you have the option to use a while loop. The structure of a while loop is more simple than a for loop, because you’re only evaluating the one condition. The loop goes round and round while the condition is true. When the condition is false, the programme breaks out of the while loop. Here’s the syntax for a while loop:

while (condition) {

And here’s some code to try. All it does is increment a variable called counter:

counter = 1
while (counter < 11) {
document.write(” counter = ” + counter + “<BR>”)

The condition to test for is counter < 11. Each time round the while loop, that condition is checked. If counter is less than eleven then the condition is true. When counter is greater than eleven then the condition is false. A while loop will stop going round and round when a condition is false.

If you use a while loop, be careful that you don’t create an infinite loop. You’d create one of these if you didn’t provide a way for you condition to be evaluated as true. We can create an infinite loop with the while loop above. All we have to do is comment out the line where the counter variable is incremented. Like this:

counter = 1
while (counter < 11) {
document.write(” counter = ” + counter + “<BR>”)

Notice the two forward slashes before counter++. This line will now be ignored. Because the loop is going round and round while counter is less than 11, the loop will never end – counter will always be 1.

Here’s the times table programme again, only now we’ve used a while loop instead of a for loop (the lines that write the result to the text area have been left out):

start = 1
end = 1
times = 2
answer = 0

while (end < 11) {
answer = start * times

The while loop calculates the 2 times tables, up to a ten times 2. Can you see what’s going on? Make sure you understand the code. If not, it’s a good idea to go back and read this section again. You won’t be considered a failure. Honest.


Do … While loops

This type is loop is almost identical to the while loop, except that the condition comes at the end:

while (condition)

The difference is that your statement gets executed at least once. In a normal while loop, the condition could be met before your statement gets executed. Don’t worry too much about do while loops.

In the next part, we’ll take a look at how to break free of a loop, and have a good look at something called a switch statement.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s