For loop
We'll use the template window to demonstrate some other features of Javascript. In previous exercises you have written a sequence of Javascript instructions. The next structure to consider is a program loop. I.e. we want the program to repeat a sequence of instructions a number of times. We will use the multiplication tables to demonstrate this. The user will be prompted for a value to be used in the table. You have already met the alert() and confirm() methods, now the prompt() method.
Modify the javascript template to add the following code and add a button to test the function.
The statement output += something is a shorthand way of writing
(new) output = (old) output + something
![]() |
By default, the program will produce the 5 times table (the default value is the second property in the prompt method, the first is the prompt string).
The HTML tags have been added to the header and a <BR> statement ends each line of the table. The working part of this program is the statement for (var i=1;i<=10;i++) { ... }. The code within the curly braces are the statements that will be repeated. In plan words the for statement can be read as "for variable i = 1; to i less than or equal to 10; increment i).
The last part of the statement i++ is Javascript (as well as Java and C++) shorthand for increment i. i.e.
|
| Attachment | Size |
|---|---|
| loops-Ex1.htm | 847 bytes |


