JavaScript Flow Control and Looping

Revision as of 19:05, 23 April 2007 by Neil (Talk | contribs) (Conditional Statements)

Revision as of 19:05, 23 April 2007 by Neil (Talk | contribs) (Conditional Statements)

One of the most powerful features of JavaScript (and every other programming or scripting language for that matter) is the ability to build intelligence and logic into your web pages. It is vital in constructing scripts to be able to have the script make decisions and repeat tasks until specified criteria are met. For example, if you are developing an e-commerce application you may want to repeatedly ask a user to enter a credit card number until a valid credit card number is entered. Alternatively, you may want your script to loop a specifc number of times through a task before moving on to the next part of the script. All of this logic and flow control is achieved using some very simple structures. These are:

Conditional Statements

  • if statements
  • if ... else ... statements

Looping Statements

  • while loops
  • do ... while loops

switch Statements

label Statements

with Statements

Conditional Statements

Conditional statements control whether a part of a script is executed depending the result of a particular expression (i.e whether an expression returns a boolean true or false value). The two types of conditional structures are if and if ... else. In this section we will take a closer look at both of these condtional structures and provide some examples of their use.

The JavaScript if Structure

The first line of an 'if structure involves the if statement followed by the expression to be evaluated in parentheses. For example:

if (i < 2)

In the above example if i is less than 2 then the expression will be evaluated as being true, otherwise it will be returned as false

The next step in structing an if statement is to specify what action should be taken if the expression is true. This is acheived by placing the lines of script to be executed in open and closing braces after the if statement:

if (i < 2)
{
document.writeln ("The value of i is less than 2");
i++;
}

Note that if there is only one line of script to be performed if the if expression is true then the braces are optional:

if (i < 2)
\tdocument.writeln ("The value of i is less than 2");