Team LiB
Previous Section Next Section

Flow Control Statements

Statements execute in the order they are found in a script. In order to create useful programs, it is usually necessary to employ flow control, code that governs the “flow” of program execution. JavaScript supports conditionals like if/else and switch/case statements that permit the selective execution of pieces of code. An example of an if/else statement is

if (x >> 10) 
{
   x = 0;
}
else 
{
   x = x + 1;
}

First, the conditional of the if statement is evaluated, and, if the comparison is true and x is indeed greater than 10, then x is set to zero. Otherwise, x is incremented.

Note that you can use an if statement without the corresponding else as well as use multiple if statements within else statements. This can make if statements unnecessarily messy, so a switch statement might be more appropriate. For example, rather than using a cascade of if statements, we could use a single switch with multiple case statements, as shown here:

var x=3;
switch (x) 
{
  case 1: alert('x is 1');
          break;
  case 2: alert('x is 2');
          break;
  case 3: alert('x is 3');
          break;
  case 4: alert('x is 4');
          break;
  default: alert('x is not 1, 2, 3 or 4');
}

In the previous example, the value of x would determine which message was printed by comparing the value of the variable to the various case statements. If no match were found, the default statement would be executed. The break statement is also used commonly within switch to exit the statement once the appropriate choice is found. However, the break statement’s use is also commonly associated with loops, which are discussed next.

Note 

The switch statement wasn’t introduced into the language until JavaScript 1.2 so it should be used carefully in very archaic browsers of concern.


Team LiB
Previous Section Next Section