Introduction To Javascript
For Loops


For loops are a very powerful tool in programming. They allow you to run statements a fixed number of times. This comes in very handy for repetitive tasks.

Exercise 2

Suppose you want to use the script from the first exercise to make the phrase Hello World appear a certain number of times on the page. Amend the script as follows and load the page. Adapt the script to give your own message. You can add HTML within the document.write statement to change the way your message is displayed.

<script type="text/javascript">
for (var i=0; i<11; i++) {
document.write("Hello World!<br>")

Study the statement that produces the for loop. The section in brackets can be confusing. There are 3 parts to the code within the brackets. The first part (var i=0) allocates the variable i to the loop and establishes its starting value as 0. The second part (i<11) sets the limit of the loop. The third part (i++) sets the amount by which i will increase each time the loop runs the code contained within; in this case the amount should increase by 1. Each time the code within the loop is run the value of i changes until it fails to satisfy the condition in part 2 of the statement. Curly braces { } mark the start and end of the code which is to be repeated.

Exercise 3

On the first page of the guide we talked about interactivity. User input is the key to interactvity. You can make this basic script interactive by allowing the user to set the limit of the loop.

Add the following statement to the line above the for statement.

var limit = prompt("Enter a number", "10");

Change the for statement to the following.

for (var i=1; i<limit; i++) {

You could also change the document.write statement as follows.

document.write(i + " Hello World!<br>")

Run the script in a page. Notice the way that you can add the value of i to the document.write statement enabling you to change the way a page loads according to user input.

Exercise 4

Amend the code that you have used in the previous exercise so that when your page loads, the user sets the number of times that the loop runs and the phrase that it repeats.