JavaScript control structures

The simple programs programs we've seen so far just ran straight through. The browser started at the beginning of the program and execution flowed through statements line by line in strict order until it reached the end. Programs like that are of very little use and we need to be able to make the program behave differently in different situations.

There are only three ways that a program can behave. These are:

Sequence: statements are executed one by one in the sequence in which they appear in the file.

Selection: the result of some test or comparison decides which group of statements is going to be executed.

Repetition: the same group of statements is executed a number (zero, one or many) of times depending on the result of some test or comparision.

Any program will have sections of sequential code, sections of selected code and sections of repeated code and these sections can be nested inside one another to an unlimited depth. These three structures are all that you need to build any program and in fact every program boils down to this general arrangement:

  1. Start with some code to set things up.
  2. Get some input from the user and decide what to do with it.
  3. Repeat step 2 as many times as is necessary.
  4. Finish with some code to tidy up.

We've already seen simple programs executing code in sequence so next we're going to look at selection where we will decide which sections of code will execute and repetition where we'll put the program into a loop.

Both these forms of program structure are controlled by some sort of test which compares two values so we'll need to look at how comparisons work in JavaScript.

MS Access technical tips

Visual FoxPro technical tips

General Tips

 

More tips from Alvechurch Data

Search page for Alvechurch Data

Searching a web site with JavaScript

Read More

Site Map

Site map of the Alvechurch Data site

Read More

Javascript while loops

JavaScript do and while loops

Read More

Javascript for loops

Javascript for loops

Read More

Repetition in Javascript

JavaScript structures for repetition

Read More