Next page | Contents page |

Conditional statements

if ... else


if (boolean expression)
  statement

or


if (boolean expression)
  statement
else
  statement

Example:


if ((x == y) && (z >= 3))
{
  r = 23.0;
  z--;
}
else if (x > y)
{
  r = -4.0;
  x++;
}
else r = 10.2;

In some programming languages there is also a keyword elseif, but not in JavaScript: use else and then if, as in the example.

switch/case


switch (expression)
{
  case value1: statements
  case value2: statements
  ...
  default: statements  
}

The expression is evaluated. If the result matches any of the case values, statement execution begins at that point and continues through all the other cases and the default section unless something prevents that. Usually the statement break; makes execution jump out of the switch statement before the next case is reached. It is important to remember to break out like this if that is required.

The default section is optional. Execution starts there if none of the values matches the result of the expression.

Example (text editor - user has pressed a key):


switch (keyCode)
{
  case insKey: insert ();
               break;
  case backKey:
  case delKey: delete ();
               break;

  default:     append (keyCode);
}

Constraints on the switch statement

These rules are more flexible than in other languages (eg, C or Java).

Next page | Contents page |