CIW Course Revision Site

JavaScript - Controlling Program Flow

CIW Website Design Manager Course Section 2, Part A1, Chapter 4

If Statement

The "If" statement is, perhaps, the most basic decision making statement in the program flow of any application.

If (condition1)
{
// Code to execute if condition1 is true
}
else if (condition2)
{
// Code to execute if condition2 is true
}
else
{
// Code to execute if neither condition1 or condition2 are true
}

The condition is any expression that evaluates to true or false. The parentheses are required and a semi-colon does not terminate the line.

While Statement

The "While" statement is a loop statement which will execute repeatedly for as long as the condition evaluates to true.

while (condition)
{
  // Code to execute while condition is true
}

If condition never evaluates to false the loop will never end and your program will, effectively, hang.

Do Statement

Also referred to as a do...while statement, which is probably more accurate. It is a variation on the "While" statement that checks the condition at the end of the loop.

do
{
  // Code to execute once and then
  // repeatedly while condition is true
}
while (condition)

Checking the condition at the end of the loop ensures that the code within the loop is always executed at least once.

For Statement

Those of you familiar with the Basic programming language may know this as a For...Next statement. It fulfils the same action, that of iterating through a section of code with a set number of values.

for (i=0; i<4; i++)
(
  // Code to execute for each iteration
}

The values after "For" need a little explanation. I like to think of the three values as Initial. Condition and Action. In the first expression i=0 the variable i is set to the value 0, the second expression tests that variable for being less than 4, the third expression increment that variable i. The code will be executed four times when i holds the values 0, 1, 2, & 3.

Switch Statement

This can be thought of as a multiple "If" statement. The variable supplied to the switch is tested for comparison against one or more values.

switch (testValue)
{
case "Tom":
  alert("Hi Tom");
case "Dick":
  alert("Hi Tom");
case "Harry":
  alert("Hi Tom");
default:
  alert("Hi No-One");
}

If a match is found, the code between the matching "case" and the following "case" will be executed.

Loop Control Commands

The commands "continue" and "break" can be placed anywhere inside a block of loop code. "continue" will move the execution back to the top of the loop, while "break" exits the loop. "continue" can only be used in a "for" or a "while" loop.

Design by Stephen

Certified Internet Webmaster

Page last Edited: 10 Nov 2011