Home and Learn: Javascript Programming Course

Javascript while loops

While loops (lowercase "w") are another programming tool you can add to your armoury. Here's the structure of a while loop:

while ( condition_to_test ) {


Instead of the word "for" this time type while. After a space, you type a pair of round brackets. Inside of the round brackets you need a condition to test. This will be evaluated to either true or false. While your conditions is still true the loop will go round and round. When it's false, the loop will end. Take this code as an example:

var counter = 1;
var answer = 0;

while (counter < 11) {

answer = answer + counter;


document.write("answer= " + answer);

Here, we have two variables, one called counter and the other, like before, called answer. Inside of the round brackets of while, we have this:

counter < 11

This will be evaluated to true or false each time round the loop. It says, "while counter is less than 11 keep looping".
To execute some code you again need a pair of curly brackets. Inside of the curly brackets, we have this:

answer = answer + counter;

Again, we want to add up the numbers 1 to 10. We're doing it the same as before. This time we're adding up whatever is in the answer variable and whatever is in the counter variable. We need to move the counter on by 1, though, each time round the loop. Otherwise the loop would never end. The second line, then, increments the counter variable:


The second time round the loop the counter variable will be 2. That's still less than 11 so the loop continues for a third time. When the counter advances to 11 the condition between the round brackets becomes false, so the loop will end.

While loops are a lot easier to use than for loops. Which one you use depends on the situation. But it's nice to master both. So try these two exercises:

Use a while loop to add up the numbers 1 to 20.

Use a while loop to print out the even number from 1 to 20. (You'll need Modulus for this. And an IF Statement.)

OK, we'll move on. Next up is arrays.

Back to the Home Page

Email us: enquiry at homeandlearn.co.uk