The JavaScript Control Structures



Navigation Aids -- This Page    Navigation Aids -- This Topic    Navigation Aids -- This Site




Review of Terms Related to This Topic





Introduction and Review

Control structures are used to alter program flow and provide an alternative to sequential program flow. Computer programs have three ways for processing statements:

Many references will indicate the case structure as a fourth structure. We have included the case structure with the selection group.

This topic is focused on JavaScript. However, we have included references and even some examples from other programming languages other than JavaScript.

Sequence

We introduced sequence structures above as one of three program structures. However, the sequence structure is really not a flow control structure and we will give it no further consideration here.





Selection

Almost all programming languages provide a way to selectively branch to particular program statements depending on a condition. JavaScript includes the if/else and the switch statements for selection control.

The if/else statement can be one-way or two-way selection. The optional else keyword is required for the two-way selection, otherwise, the if keyword will suffice for a one-way selection. Using the else/if structure can provide multiple selections much like the switch statement.


if (conditional expression1)   a statement or block else if (conditional expression2)   a statement or block else if (conditional expression3)   a statement or block ..... else   a statement or block

The switch statement is shown below. It utilizes the case and default keywords and requires the break statement to force termination at exit points.

switch (expression) { case value1: statements1    break; // the break statement causes an immediate exit from the switch structure case value2: statements2    break;     ...... case valuen: statements    break; default: statements; }



Repetition

Most all programming languages provide ways to loop through a particular set of statements. The loop is controlled by a conditional expression within a control statement. The expression is called a loop condition. The loop condition acts as a decision maker and it is a logical expression that evaluates to a boolean value. The condition that will terminate the loop is tested on each iteration. As long as the test remain true, the loop is executed one more time. Once the loop condition tests to be false the loop is terminated. There are typically four types of loop control methods:

We have used the while statement in the examples below. In a couple of examples, we used the Java version of the while statement. We are using Java because two of the loop control structures really need to accept input. And JavaScript does not have any native capabilities for input.





Supporting Statements

There are a number of statements that support control structures. They aid in program flow (around, in, and out) of looping body statements.





Continue Statement

We need to make two distinctions here concerning exiting a loop. You can exit the loop body. And, you can exit the entire control structure. The continue statement will exit the loop body, however, program flow starts again at the loop control statement. So, the iteration continues.





Break Statement

The break statement will exit the control structure. Within loops, the break statement is typically used to exit a loop when your loop body logic has determined the loop iteration is no longer necessary. The break statement will jump to the end of the control structure and begin execution with the next statement in sequence following the loop. With nested control structures, breaking from an inner loop will send you out to the next level of nesting.

The break statement is also used with the switch statement.





Block Statement

The block statement is that group of statements enclosed within curly braces " { } ". All of the repetition control statements make use of the block statement. When referring to loops, the block statement contains the loop body statements. The if/else control structure also uses the block statement.





Label Statement

We are interested in label statements inside the loop body (or the block). Almost any statement may have a label. Both the break and continue statements may specify a label. When they specify a label such as:

continue appleseed; // jump to statement with label identifier of applepseed

The program execution will resume execution at the statement with the designated label. This is in effect a "branch" or "jump" or "goto". The dreaded "goto"!!





Recursive Functions

A recursive function is a function that calls itself. The body of the recursive function contains a statement that invokes another copy of itself before completing the current call. These successive recursive calls will continue until a base case is reached. The base case causes the return to the caller and successive returns occur until the original call is reached.

Recursion methods have the following characteristics:

Recursion methods have the following behavior:

It helps to think of recursive methods as a chain of connected modules. The chain is linked by caller to callee going successively down to the last call (the base case). Then the successive return path begins. This path is the reverse of the downward path and progresses upward through the module chain.

Consider the factorial computation. The formula is:

n!=n*(n-1)*(n-2)*.....*1

Given the above formula, the computation for 4 factorial (4!) is:

4!=4*3*2*1 = 24

A recursive function for the factorial problem is shown here:

//recursive function var n = 0; function factorial(n) { // the following selection control structure controls the recursion  if (n == 0)    return 1; // the base case  else    return n * factorial(n-1); // the recursive case } alert(factorial(4)); // pass four to the recursive function

When n == 0, the base case is executed where the value one is returned to the caller. The factorial formula above (n!=n*(n-1)*(n-2)*.....*1) ends with the multiplication by one. The base case returns this one here. When the selection structure is not (n == 0), then the recursive case is executed.

Here is another example of a Perl program that calculates the Fibonacci number.


#!c:\perl\bin\perl.exe -w # demo of recursive fibonacci subroutine # a Fibonacci series: 0,1,1,2,3,5,8,13,21,.... # each subsequent F number is the sum of the previous two F numbers   # set the array   @samplevalues = ( 0, 1, 2, 3, 4, 5, 7, 10, 22 );   # calculate and print the fibonacci value of all the above values foreach ( @samplevalues ) {   print "fibonacci( $_ ) = ", fibonacci( $_ ), "\n"; }   # fibonacci recursively calculates the fibonacci number of the argument   sub fibonacci {  my $number = shift(@_); # get the argument, always sent in a list; here only one entry  if ( $number == 0 or $number == 1 ) {    return $number; # the base case  }  else {    return fibonacci( $number - 1 ) + # the recursive case    fibonacci( $number - 2 );  } }



Comparing Iteration to Recursion

Many times there are two ways to solve a problem; iteration and recursion. How should you determine what method is most appropriate for your problem?





Language Statement Comparisons For Selection


The Selection Control Structures
JavaScript VB Java Cobol IBM 360/370 Assembler
if/else if/else if/else if/then/else BC (branch on condition)
and others
switch/case case switch/case evaluate/when No specific instruction,
you can build equivalent




Language Statement Comparisons For Repetition

The table below provides a comparison of JavaScript's program language repetition control statements to the near equivalent in other program languages.

The Repetition Control Structures
JavaScript VB Java Cobol Comment
while for/next while perform/times Assembler has a BCT (branch on count) instruction that acts as a counter control.
do/while do/loop do/while perform/until The VB do/loop has both the do/while and do/until feature
for for/next for perform/times As a counter control mechanism, the for statement does the same process as the while construct.
for/in N/A N/A N/A Java does not support the for/in statement.


Top            

Rx4AJAX        About Us | Topic Index | Contact Us | Privacy Policy | 2008 This Site Built By PPThompson