Skip to content
Science, Maths & Technology

The Syntax of the 'for' Loop

Updated Monday 29th June 2015

Learn how a for loop is structured and how to write them.

A man sits on a sofa, checking a laptop computer Copyright free image Icon Copyright free: Startupstockphotos via Pixabay

for (declare and initialise counter; test value of counter; change value of counter)

Points to note

  • The use of the semicolons as separators.
  • It is not mandatory to declare the loop counter within the for statement's header. It could be declared along with other variables at the start of the program. However, here we follow the convention in the syntax above, as this makes clear the special purpose of the variable.
  • The body of the for loop can consist of several statements, wrapped together into a single compound statement by means of curly braces.

The effect of a for loop can be found in the image below.

How a for loop works. Process statements before the for loop. Initialise the counter with its starting value. Test: Has the counter passed its stopping value. If it has not, execute the body of the for loop, then increment or decrement the counter and check again. If it has, execute statements after the for loop.

Question: Suppose that a for statement is used for a programming task that involves six iterations.

(a) How many times will the initialisation part of the for loop be executed?

(b) How many times will the Boolean condition be evaluated?

(c) How many times will the statement changing the value of the counter be executed?


(a) Once. The counter is only initialised once regardless of the number of iterations.

(b) Seven times. The condition will need to evaluate to true six times, once for each iteration of the code in the body of the for loop; on the seventh attempt it will evaluate to false.

(c) Six times. The statement to increment or decrement the value of the counter is executed at the end of each iteration.

Activity 1

Here is the code from for_syntax_activity_1.html.

for (var line = 1; line <= 6; line = line + 1)
    document.write('I must pay attention in class' + '<BR>');
document.write('I\'ve finished!');

What do you think the output will be? Run the program to find out.


The program will display six times, on separate lines:

I must pay attention in class

and then I've finished! on a new line.

Note that in this example the value of the counter variable line is needed simply to keep track of the number of iterations. In our earlier examples the value of the counter was used by the code in the body of the loop as well.

Activity 2

The following code is from for_syntax_activity_2.html.

for (var count = 1; count <= 6; count = count + 1)

(a) Write down what you think the program does. Run the program and see if you are correct.

(b) Open the file in the text editor and amend the program so that the user is prompted to enter a value for the length of a line of asterisks to be displayed, such that, for example, an input of 3 results in an output of ***. Save your changes and run the program.

(c) Further amend the program so that as well as being prompted for the length of the line, the user is also prompted for the character to be output (so that it need not be *). Save your changes and run your program.

(d) Further amend the program so that, instead of a horizontal line of characters the program outputs a vertical line. For example, an input of + for the character and 3 for the length will give the following output:


Save your changes and run your program.


(a) The program displays six asterisks in a line, i.e. ******.

(b) Here is our solution.

var length;
length = window.prompt('Please enter the length of your
length = parseFloat(length);
for (var count = 1; count <= length; count = count + 1)

(c) The following amendments to the code are required:

  • declare a variable to hold the chosen character, say character;
  • add the following line before the for loop:
    • character = window.prompt('Please enter your chosen character','');
  • change the body of the for loop to:
    • document.write(character);

(d) The body of the for loop above needs modifying to include a line break after each character, as follows:

document.write(character + '<BR>');

You might also have replaced the variable length by one with a name such as number, and modified the prompt to the user.

You will find a working solution in for_syntax_solution_2.html.

Activity 3

The file for_syntax_activity_3.html contains a partially completed program to calculate the average exam score for a group of five students. For each student, the user is prompted to enter a score and this score is added to the total so far. Once the scores for the five students have been entered and totalled, the average score is calculated and output. We have provided you with the code to calculate the average and display it. You should add the code to prompt for and read in the scores, convert them to numbers and add them to the total. Open the file in your text editor and add your code in the spaces indicated. Test your program by running it with several sets of five scores.

If you have difficulty you might find the hints which follow this activity helpful.


Here is our completed code.

var total;      // total of scores so far
var score;      // score for a single student
var average;    // average score

// Insert code to initialise total
total = 0;

/* insert code for a for loop to read in and add the 5 student scores to total */

for (var count = 1; count <= 5; count = count + 1)
    score = window.prompt('please enter next score','');
    score = parseFloat(score);
    total = total + score;
average = total / 5;
document.write('average score is ' + average + '<BR>');

Did you get your loop condition correct?

Did you remember to use parseFloat() to convert your input string into a number?

You will find a working solution in for_syntax_solution_3.html.

Hints for writing programs with for loops

  • Do you need any variables outside the loop to hold any data? If so, declare it/them.
  • Do you need any statements to be executed before the loop?
  • In order to write the loop control statement (the top of the for loop), you need to consider where you want the counter to start, where you want it to end, and how you want it to change at each execution of the body of the loop.
  • In order to write the body of the for loop, you need to work out what should happen during each execution of the loop body.
  • Do you want any statements to be executed after the loop?

Activity 4

Within for_syntax_activity_4.html is a copy of the code used in the first activity.

for (var count = 1; count <= 10; count = count + 1)
    document.write('Count is ' + count + '<BR>');
document.write('Thank you' + '<BR>');

Open the file in the text editor and see if you can replace the code for the for loop by code for a while loop which does exactly the same thing. Run the original program and your new one to check that they both do the same thing.


Here is our solution.

var count;

count = 1;
while (count <= 10)
document.write('Count is ' + count + '<BR>');
count = count + 1;
document.write('Thank you' + '<BR>');

As you can see, the way the code works is very similar in both cases:

  • the counter variable is initialised to the same value;
  • the same condition is tested before each iteration of the loop;
  • the counter is updated at the end of each iteration (though in the case of the while loop this is done within the body of the loop).

You will find a working solution in for_syntax_solution_4.html.

Where you have a for loop, it is always possible to write an equivalent while loop, but we recommend that when you know how many iterations are required you use a for loop, which makes the number of repetitions much clearer.

Where you have a while loop, it is not usually possible to write an equivalent for loop because while loops are normally used where you don't know in advance how many iterations will be required.

You'll now be moving onto Strings and for Loops, which will show you how to use strings in your loops, as well as looking at some of the more interesting properties that objects have.



For further information, take a look at our frequently asked questions which may give you the support you need.

Have a question?