Working with JavaScript

So far we have created static web pages: pages whose content and layout do not change. Now we'll start working with scripts to modify the content and appearance of your pages.

In the lecture on forms, we heard about server side programs that your pages could access when processing forms. There are several disadvantages to server side programs.

  1. You must be connected to the web server in order to access the program.
  2. Only a programmer can create these programs.

  3. The system administrator can place limitations on who can access these programs.
  4. The system administrator has to be aware of unauthorized users accessing the server and overloading the system or worse having access to the system and making changes.

Client side programs solve some of these problems because the program can be tested locally, the work of the program is not associated with a single server and so distributes the work load, and they can faster than a server side program because the user does not have to wait for data to be sent to or from the server. Client side scripts will never totally replace server side programs because there are some things that must have access to a database or other information stored only on the server.

Java is a programming language that can be used as a client side program, but it is a compiled language which means you need the Java Developer's Kit (JDK) to convert the source code into an executable applet. This means that you need to understand programming and have access to the tools to do it. This also means that many people who want to design for the web didn't really have access to java. To address this, developers from Netscape and Sun Microsystems created a subset of Java called JavaScript which is an interpreted language. Each instruction in JavaScript is converted to an executable instruction each time the program is run. There is no need for the JDK, the browser simply needs to know how to handle it. JavaScript can also be inserted directly into html or xhtml files, or placed into a separate file that is linked to a web page. It is not as powerful as java, but it is easier to use and will meet most of your needs.

What is JavaScript?

Java JavaScript
A compiled language An interpreted language
Requires the JDK to create applets Requires a text editor
Requires a java virtual machine or interpreter to run the applet Requires a browser that can interpret JavaScript code
Applet files are distinct from the html code JavaScript programs are integrated and can be placed within html
Source code iis hidden from the user Source code is accessible to the user
Powerful, requires programming knowledge and experience Simpler, requires less programming knowledge and experience
Secure:programs cannot write content to the hard disk Secure: programs cannot write content to the hard disk, but there are more security holes than in java.
Programs run on the client side Programs run on the client side.

JavaScript has been revised several times and Internet Explorer uses a slightly different version called Jscript which is almost the same as JavaScript, but some commands are not supported in one or the other. You should always test your JavaScript in a variety of browsers.

What can a JavaScript program do?

JavaScript gives HTML designers a programming tool. HTML authors are normally not programmers, but JavaScript is a scripting language with a very simple syntax! Almost anyone can put small "snippets" of code into their HTML pages.

JavaScript can put dynamic text into an HTML page: A JavaScript statement like this:

document.write("<h1>" + name + "</h1>")

can write a variable text into an HTML page.

JavaScript can react to events: A JavaScript program can be set to execute when something happens, like when a page has finished loading or when a user clicks on an HTML element.

JavaScript can read and write HTML elements: A JavaScript program can read and change the content of an HTML element.

JavaScript can be used to validate data: A JavaScript program can be used to validate form data before it is submitted to a server. This saves the server from extra processing.

JavaScript can be used to detect the visitor's browser: A JavaScript program can be used to detect which model of browser the user has, and (depending on on the browser) load another page specifically designed for that browser.

JavaScript can be used to create cookies: A JavaScript program can be used to store and retrieve information on the visitor's computer.

Inserting JavaScript into a web page

First you need to use the script element. You can either embed the script in the page or have it in an external file.

To embed ths script in a page:

<script type="mime type" >
script commands and comments
</ script>

where "mime type" is the MIME type of the language in which the program is written. It is required in xhtml and should always be used in html too. The mime type for JavaScript is "text/JavaScript". You can also (probably with Internet Explorer) use vbscript which is a Microsoft product; its mime type is "text/vbscript".

To use a script in an external file:

<script src="url" type="mime type" ></script>

where url is the location of the file with the JavaScript.

Comments in JavaScript can be either on a single line or multiple lines:

// single line comment

/* multiline
comments can be
spread over several lines */

You should always comment your JavaScript, just as you should comment your html so you can remember what you were doing. Another reason for comments is to hide your script from older browsers. Older browsers that don't support JavaScript may display program code on the web page which is something you really don't want. So you hide the script from them by using a combination of html and JavaScript comments like this:

<script type=”text/JavaScript”>
<!-- hide from non-JavaScript browsers
JavaScript commands
//stop hiding from older browsers -->
</script>

You can also specify alternative content by using the noscript element:

<noscript>
other content
</noscript>

<noscript>
<p>This web page requires JavaScript. If you can turn on JavaScript, you should do so and reload the page.</p>
</noscript>

Where to Put the JavaScript

JavaScripts in a page will be executed immediately while the page loads into the browser. If you want a script to be executed because of an event or when it is called you put it in the head:

<html>
<head>
<script type="text/JavaScript">
....
</script>
</head>

Scripts to be executed when the page loads go in the body section. When you place a script in the body section it will generate some of the content on the page:

<html>
<head>
</head>
<body>
<script type="text/JavaScript">
....
</script>
</body>
</html>

There is no limit to the number of scripts in your document, so you can have scripts in both the body and the head section.

<html>
<head>
<script type="text/JavaScript">
....
</script>
</head>
<body>
<script type="text/JavaScript">
....
</script>
</body>

Using an External JavaScript Program

Sometimes you might want to run the same JavaScript program on several pages, without having to write the same script on every page.

To simplify this, you can write a JavaScript in an external file. Save the external JavaScript file with a .js file extension.

Note: The external script cannot contain the <script> tag!

To use the external script, point to the .js file in the "src" attribute of the <script> tag:

<html>
<head>
<script src="xxx.js"></script>
</head>
<body>
</body>
</html>

JavaScript is an object-oriented language. This means that objects are manipulated by using methods. Objects can be the web page document itself, headings, list items, images, frames, applets, the browser window or the browser.

Writing output to a web page

There are two waysto do this:

The writeln method is used when you want to keep the line breaks within the text string, where "text" is a string of characters to be displayed.

You can enclose the text within either single or double quotes. This allows you to put html which includes quotation marks as the text:

document.write("<h2> Heading </h2>&");

document.write('<p style="text-align:center"> This is centered </p>');

Variables and Data

The write() method so far is not really useful; in fact it is actually more work. So we need a little more to make it worthwhile. To do this you need to have variables. A variable is a named item that stores information. Information that can be created in one part of your program and then used in another part.

You could create a variable for your age:

Age=21;

Then you can output the contents of the variable with the document.write() statement:

document.write(Age);

or you can combine text and a variable with the concatenation symbol (+):

document.write("I am " + Age + " years old.");

Rules for names of variables

Variable types

Declaring a variable

You need to create variables before you can use them. There are a couple of different ways of doing this:

var Age;
var name = "Jorja";
title="Instructor";

Working with dates.

In order to retrieve the date from the computer you need to have a "date object". This is another kind of variable type. There are two ways to declare a date object:

thedate = new Date("month day, years, hours:minutes:seconds");
thedate = new Date("April 19, 2006, 16:13:00");

or

thedate = new Date(year, month, day, hours, minutes,seconds);
thedate = new Date(2006,4,19,16,13,00);

or store the current date and time by

thedate = new Date();

Because of the way JavaScript stores the contents of the date object, you have to get the parts in a particular way.

To get the day of the month:

thisday=thedate.getDate();

To get the month:

thismonth=thedate.getMonth() + 1;

(You have to add one because JavaScript stores months as numbers starting with January as 0)

To get the year:

this year=thedate.getFullYear();

(There is a getYear() method that returns the last 2 digits of the year.)

Other date methods available are:
getMinutes();
getSeconds();
getHours();
getTime();

Arithmetic operators

Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division
% Gives the remainder after division
++ Adds 1 to a variable
-- Subtracts 1 from a variable
- Changes the sign of a variable

Examples with arithmetic:

var x=10;
var y = 2;
var z;

z = x + y; // z will have the value 12
z = x – y; //z will have the value 8
z = x * y; //z will have the value 20
z = x / 2; //z will have the value 5
z = y % x; //z will have the value 2
x++; //x now has the value 11
y--; // y now has the value 1

The = (equal sign) is actually an assignment operator. And there are several variations of it:

x = x+y;
x += y; //these two do the same thing
x = x + 1;
x += 1;
x++;// these 3 all do the same thing

The + operator is also used to concatenate strings and the += can be used with strings too.

You can do simple math on numeric variables, but JavaScript has several math method objects for more complicated math. These objects are accessed by

value = Math.method(variable);

where method is the math operation you want to use on the variable and value is the result.

For instance, the "Absolute Value" method is Math.abs():

answer = Math.abs(-4); //answer contains 4

Math method

Description
Math.abs(number) Returns the absolute value of number
Math.sin(number) Calculates the sine of the number where number is an angle expressed in radians
Math.cos(number) Calculates the cosine of the number where number is an angle expressed in radians
Math.round(number) Rounds number to the nearest integer
Math.ceil(number) Rounds number up to the next-highest integer
Math.floor(number) Rounds number down to the next lowest integer
Math.random() Returns a random number between 0 and 1

Conditional Statements

Very often when you write code, you want to perform different actions for different decisions. You can use conditional statements in your code to do this.

JavaScript has the following conditional statements:

Before we learn how to write conditional statements we need to know how to make comparisons in JavaScript.

Comparison Operators

Operator Description Example
== is equal to 5==8 returns false
=== is equal to (checks for both value and type) x=5
y="5"
x==y returns true
x===y returns false
!= is not equal 5!=8 returns true
> is greater than

5>8 returns false

< is less than 5<8 returns true

>=

is greater than or equal to 5>=8 returns false
<= is less than or equal to 5<=8 returns true

Logical Operators

Operator

Description Example
&& and x=6
y=3
(x < 10 && y > 1) returns true
|| or x=6
y=3
(x==5 || y==5) returns false
! not x=6
y=3
!(x==y) returns true

Syntax for if

if (condition)
{
code to be executed if condition is true
}
Note that "if" is written in lowercase letters. Using uppercase letters (IF) will generate a JavaScript error!

Example 1
<script type="text/JavaScript">
//Write a "Good morning" greeting if
//the time is less than 10
var d=new Date()
var time=d.getHours()
if (time<10)
{
document.write("<b>Good morning</b>")
}
</script>

Example 2
<script type="text/JavaScript">
//Write "Lunch-time!" if the time is 11
var d=new Date()
var time=d.getHours()
if (time==11)
{
document.write("<b>Lunch-time!</b>")
}
</script>

Note: When comparing variables you must always use two equals signs next to each other (==)! Notice that there is no ..else.. in this syntax. You just tell the code to execute some code only if the specified condition is true.

Syntax for if ...else

if (condition)
{
code to be executed if condition is true
}
else
{
code to be executed if condition is not true
}

Example
<script type="text/JavaScript">
//If the time is less than 10,
//you will get a "Good morning" greeting.
//Otherwise you will get a "Good day" greeting.
var d = new Date()
var time = d.getHours()
if (time < 10)
{
document.write("Good morning!")
}
else
{
document.write("Good day!")
}
</script>

Syntax for if.. else if .. else

if (condition1)
{
code to be executed if condition1 is true
}
else if (condition2)
{
code to be executed if condition2 is true
}
else
{
code to be executed if condition1 and
condition2 are not true
}

Example
<script type="text/JavaScript">
var d = new Date()
var time = d.getHours()
if (time<10)
{
document.write("<b>Good morning</b>")
}
else if (time>10 && time<16)
{
document.write("<b>Good day</b>")
}
else
{
document.write("<b>Hello World!</b>")
}
</script>

Syntax for switch statement

switch(n)
{
case 1:
execute code block 1
break
case 2:
execute code block 2
break
default:
code to be executed if n is
different from case 1 and 2
}

Switch uses a single expression n (most often a variable), that is evaluated once. The value of the expression is then compared with the values for each case in the structure. If there is a match, the block of code associated with that case is executed. Use break to prevent the code from running into the next case automatically.

Example
<script type="text/JavaScript">
//You will receive a different greeting based
//on what day it is. Note that Sunday=0,
//Monday=1, Tuesday=2, etc.
var d=new Date()
theDay=d.getDay()
switch (theDay)
{
case 5:
document.write("Finally Friday")
break
case 6:
document.write("Super Saturday")
break
case 0:
document.write("Sleepy Sunday")
break
default:
document.write("I'm looking forward to this weekend!")
}
</script>

Popup boxes

JavaScript has 3 kinds of popup boxes: alert, confirm and prompt:

Alert Box

An alert box is often used if you want to make sure information comes through to the user. When an alert box pops up, the user will have to click "OK" to proceed.

Syntax:

alert("sometext")

Confirm Box

A confirm box is often used if you want the user to verify or accept something. When a confirm box pops up, the user will have to click either "OK" or "Cancel" to proceed.

>

If the user clicks "OK", the box returns true. If the user clicks "Cancel", the box returns false.

Syntax:

confirm("sometext")

Prompt Box

A prompt box is often used if you want the user to input a value before entering a page. When a prompt box pops up, the user will have to click either "OK" or "Cancel" to proceed after entering an input value.

If the user clicks "OK" the box returns the input value. If the user clicks "Cancel" the box returns null.

Syntax:

prompt("sometext","defaultvalue")

JavaScript Loops

Very often when you write code, you want the same block of code to run over and over again in a row. Instead of adding several almost identical lines in a script we can use loops to perform a task like this.

In JavaScript there are two different kind of loops:

The for Loop

The for loop is used when you know in advance how many times the script should run. The syntax looks like this:

for (var=startvalue;var<=endvalue;var=var+increment)
{
code to be executed
}

>

Example

This example defines a loop that starts with i=0. The loop will continue to run as long as i is less than, or equal to 5. i will increase by 1 each time the loop runs.

Note: The increment parameter could also be negative, and the <= could be any comparison statement.

<html>
<body>
<script type="text/JavaScript">
var i=0
for (i=0;i<=5;i++)
{
document.write("The number is " + i)
document.write("<br />")
}
</script>
</body>
</html>

The resultof running this is:

The number is 0
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5

The while loop

The while loop is used when you want the loop to execute and continue executing while the specified condition is true. The syntax looks like this:

while (var<=endvalue)
{
code to be executed
}

Note: The <= could be any comparing statement.

Example

This example defines a loop that starts with i=0. The loop will continue to run as long as i is less than, or equal to 5. i will increase by 1 each time the loop runs.

<html>
<body>
<script type="text/JavaScript">
var i=0
while (i<=5)
{
document.write("The number is " + i)
document.write("<br />")
i=i+1
}
</script>
</body>
</html>

The result of running this is:

The number is 0
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5

Functions in JavaScript

You can also create functions in JavaScript. A function is a series of commands that performs a task. A function has a function name that identifies it, parameters that are the values used by the function, and the commands that make up the body of the function. The general syntax is:

function func_name(parameters)
{
JavaScript commands
}

Not all functions require parameters. If there none you still need the empty parentheses (). The curly braces {} are used to mark the beginning and end of the commands that belong to the function. Function names are case sensitive and must begin with a letter or underscore and cannot contain any spaces.

A function must be defined before it can be used. You can either put your functions in the head or when they are debugged and working correctly, move them into an external file which will allow you to use them in multiple web pages.

Function Example
<html>
<head>
<title> Java Script Examples </title>
<script type="text/JavaScript">
<!-- hide from non JavaScript browsers
function triarea(base,height)
{
var answer = .5 * base * height;
return answer;
}
//stop hiding -->
</script>
</head>
<body>
<br>
<script type="text/JavaScript">
<!-- hide from non JavaScript browsers
var area = triarea(5,9.4);
document.write("The area of a triangle with a base of 5 and a height of 9.4 is "+ area + "<br>");
//stop hiding -->
</script>
<br>
</body>
</html>

Example to show how many more days left in this semester.

<html>
<head>
<title>Java Script Examples</title>
</head>
<body>
<br>
<script type="text/JavaScript">
<!-- hide from non JavaScript browsers
var month="April";
var thedate;
var enddate = new Date("May 12, 2007");
var daycount;
document.write("<h1 style=text-align:center> Java Script Examples </h1>");
document.write("<p style=text-align:center>" + month +"</p>");
thedate = new Date();
document.write("The date is " + thedate + "<br>");
document.write("The day is " + thedate.getDate() + " and the month is ");
document.write(thedate.getMonth()+1 + " and the year is " + thedate.getFullYear() + "<br>");
document.write("The time is exactly: " + thedate.getHours() + ":" + thedate.getMinutes() + ":" + thedate.getSeconds() + "<br>");
daycount = (enddate-thedate)/(1000*60*60*24);
daycount = Math.round(daycount);
document.write("Days left in the semester: " + daycount + "<br>");
//stop hiding -->
</script>
<br>
</body>
</html>

Events

By using JavaScript, you have the ability to create dynamic web pages. Events are actions that can be detected by JavaScript.

Every element on a web page has certain events which can trigger JavaScript functions. For example, we can use the onClick event of a button element to indicate that a function will run when a user clicks on the button. We define the events in the HTML tags.

Examples of events:

Note: Events are normally used in combination with functions, and the function will not be executed before the event occurs!

onload and onUnload

The onload and onUnload events are triggered when the user enters or leaves the page. The onload event is often used to check the visitor's browser type and browser version, and load the proper version of the web page based on the information.

Both the onload and onUnload events are also often used to deal with cookies that should be set when a user enters or leaves a page. For example, you could have a popup asking for the user's name upon his first arrival to your page. The name is then stored in a cookie. Next time the visitor arrives at your page, you could have another popup saying something like: "Welcome John Doe!".

onFocus, onBlur and onChange

The onFocus, onBlur and onChange events are often used in combination with validation of form fields.

Below is an example of how to use the onChange event. The checkEmail() function will be called whenever the user changes the content of the field:

<input type="text" size="30"
id="email" onchange="checkEmail()">;

onSubmit

The onSubmit event is used to validate all form fields before submitting it.

Below is an example of how to use the onSubmit event. The checkForm() function will be called when the user clicks the submit button in the form. If the field values are not accepted, the submit should be canceled. The function checkForm() returns either true or false. If it returns true the form will be submitted, otherwise the submit will be canceled:

<form method="post" action="xxx.htm"
onsubmit="return checkForm()">

onMouseOver and onMouseOut

The onMouseOver and onMouseOut events are often used to create "animated" buttons.

Below is an example of an onMouseOver event. An alert box appears when an onMouseOver event is detected:

<a href="http://www.w3schools.com"
onmouseover="alert('An onMouseOver event');return false">
<img src="w3schools.gif" width="100" height="30">
</a>

VBScript

What is VBScript? it is a lightweight programming language that is a light version of Microsoft's Visual Basic.

You put VBScript in an HTML document the same way you put JavaScript into an html document:

<html>
<head>
</head>
<body>
<script type="text/vbscript">
document.write("Hello from VBScript!")
</script>
</body>
</html>

To insert a script in an HTML document, use the <script> tag. Use the type attribute to define the scripting language:

<script type="text/vbscript">

How to Handle Older Browsers

Older browsers that do not support scripts will display the script as page content. To prevent them from doing this, you can use the \ HTML comment tag:

<script type="text/vbscript">
<!--
some statements
-->
</script>

Rules for Variable Names in VBScript

Declaring Variables in VBScript

You can declare variables with the Dim, Public or the Private statement, like this:

dim name
name=some value

Now you have created a variable. The name of the variable is "name". You can also declare variables by using its name in your script. Like this:

name=some value

Now you have also created a variable. The name of the variable is "name". However, the last method is not a good practice, because you can misspell the variable name later in your script, and that can cause strange results when your script is running. This is because when you misspell (for example) the "name" variable to "nime" the script will automatically create a new variable called "nime". To prevent your script from doing this you can use the "Option Explicit" statement. When you use this statement you will have to declare all your variables with the dim, public or private statement. Put the Option Explicit statement on the top of your script. Like this:

option explicit
dim name
name=some value

Assigning Values to Variables in VBScript

You assign a value to a variable like this:

name="Jorja"
i=200

The variable name is on the left side of the expression and the value you want to assign to the variable is on the right. Now the variable "name" has the value "Jorja".

Array Variables

Sometimes you want to assign more than one value to a single variable. Then you can create a variable that can contain a series of values. This is called an array variable. The declaration of an array variable uses parentheses ( ) following the variable name. In the following example, an array containing 3 elements is declared:

dim names(2)

The number shown in the parentheses is 2. We start at 0 so this array contains 3 elements. This is a fixed-size array. You assign data to each of the elements of the array like this:

names(0)="Tove"
names(1)="Jani"
names(2)="Stale"

Similarly, the data can be retrieved from any element using the index of the particular array element you want. Like this:

mother=names(0)

You can have up to 60 dimensions in an array. Multiple dimensions are declared by separating the numbers in the parentheses with commas. Here we have a two-dimensional array consisting of 5 rows and 7 columns:

dim table(4, 6)

VBScript Procedures

We have two kinds of procedures: The Sub procedure and the Function procedure.

A Sub procedure is a series of statements, enclosed by the Sub and End Sub statements. It can perform actions, but does not return a value. It can take arguments that are passed to it by a calling procedure. If it has no arguments, its heading must include an empty set of parentheses (). The structure looks like this:

Sub mysub()
some statements
End Sub

or

Sub mysub(argument1,argument2)
some statements
End Sub

A Function procedure is a series of statements, enclosed by the Function and End Function statements. It can perform actions and can return a value. It can take arguments that are passed to it by a calling procedure. If it has no arguments, its heading must include an empty set of parentheses (). It returns a value by assigning a value to its name. The structure looks like this:

Function myfunction()
some statements
myfunction=some value
End Function

or

Function myfunction(argument1,argument2)
some statements
myfunction=some value
End Function

Calling a Sub or Function Procedure in VBScript

When you call a Function in your code, you do so like this:

name = findname()

Here you call a Function called "findname". The function returns a value that will be stored in the variable "name".

Or, you can do like this:

msgbox "Your name is " & findname()

Here you also call a Function called "findname". The Function returns a value that will be displayed in the message box.

When you call a Sub procedure you can use the Call statement, like this:

Call MyProc(argument)

Or you can omit the Call statement, like this:

MyProc argument

Conditional Statements in VBScript

Very often when you write code, you want to perform different actions for different decisions. You can use conditional statements in your code to do this. In VBScript we have three conditional statements:

You should use the If...Then...Else statement if you want to execute some code if a condition is true or select one of two blocks of code to execute.

If you want to execute only one statement when a condition is true, you can write the code on one line:

if i=10 Then msgbox "Hello"

There is no ..else.. in this example. You just tell the code to perform one action if the condition is true (in this case if i=10).

If you want to execute more than one statement when a condition is true, you must put each statement on separate lines and end the statement with the keyword "end if". For instance:

if i=10 Then
msgbox "Hello"
i = i+1
end if

There is no ..else.. in this example either. You just tell the code to perform multiple actions if the condition is true.

If you want to execute a statement if a condition is true and execute another statement if the condition is not true, you must add the "else" keyword, like this:

if i=10 then
msgbox "Hello"
else
msgbox "Goodbye"
end if

The first block of code will be executed if the condition is true, and the other block will be executed otherwise (if i is not equal to 10).

You can use the if...then...elseif statement if you want to select one of many blocks of code to execute. For instance:

if payment="Cash" then
msgbox "You are going to pay cash!"
elseif payment="Visa" then
msgbox "You are going to pay with visa."
elseif payment="AmEx" then
msgbox "You are going to pay with American Express."
else
msgbox "Unknown method of payment."
end if

You can also use the "select case" statement if you want to select one of many blocks of code to execute. It looks like this:

select case payment
case "Cash"
msgbox "You are going to pay cash"
case "Visa"
msgbox "You are going to pay with visa"
case "AmEx"
msgbox "You are going to pay with American Express"
case Else
msgbox "Unknown method of payment"
end select

Looping Statements in VBScript

Very often when you write code, you want to allow the same block of code to run a number of times. You can use looping statements in your code to do this. In VBScript there are four looping statements:

You can use a For...Next statement to run a block of code, when you know how many repetitions you want. You can use a counter variable that increases or decreases with each repetition of the loop, like this:

For i=1 to 10
some code
Next

The For statement specifies the counter variable (i) and its starting and ending values. The Next statement increases the counter variable (i) by 1. Using the keyword "Step", you can increase or decrease the counter variable by the value you specify. In the example below, the counter variable (i) is increased by two each time the loop \ repeats.

For i=2 To 10 Step 2
some code
Next

To decrease the counter variable, you must use a negative Step value. You must specify an end value that is less than the start value. In the example below, the counter variable (i) is decreased by two each time the loop repeats.

For i=10 To 2 Step -2
some code
Next

You can exit a For...Next statement with the keyword "Exit For" keyword.

A For Each...Next loop repeats a block of code for each item in a collection, or for each element of an array. For example:

dim cars(2)
cars(0)="Volvo"
cars(1)="Saab"
cars(2)="BMW"
For Each x in cars
document.write(x & "<br />")
Next

You can use Do...Loop statements to run a block of code when you do not know how many repetitions you want. The block of code is repeated while a condition is true (using the keyword "While") or until a condition becomes true (using the keyword "Until").

Example 1 using While:
Do While i>10
some code
Loop<

If i intially equals 9, the code inside the loop above will never be executed.

Example 2 using While:
Do
some code
Loop While i>10

The code inside this loop will be executed at least one time, even if i is less than 10.

Example 1 using until:
Do Until i=10
some code
Loop

If i equals 10, the code inside the loop will never be executed.

Example 2 using Unitl:
Do
some code
Loop Until i=10

The code inside this loop will be executed at least one time, even if i is equal to 10.

You can exit a Do...Loop statement with the keyword "Exit Do".

Example using Exit Do
Do Until i=10
i=i-1
If i<10 Then Exit Do
Loop

The code inside this loop will be executed as long as i is different from 10, and as long as i is greater than 10.

Return to main