Understanding Control Structure Syntax

The basic syntax of a control structure is:

type of control ( control statement ) { block of statements to execute, based on the value of the control statement ; }

The result of the control statement defines whether or not the statements in the control block are executed. Statements outside the control block are always executed. The following table describes three JavaScript control structures and their syntax.

Control

Explanation

Syntax

If

An if tests the condition of a control statement, using the comparison or logical operators in the JavaScript Operators table.

The body statements execute only if the condition tests true.

if (condition returning true or false)
{
  statements;
}
statements executed after control;

If…else

An if...else tests the condition of a control statement, using the comparison or logical operators in the JavaScript Operators table.

The body of the if executes only when the condition tests true. The body of the else executes if the condition tests false.

if (condition returning true or false)
{
  statements;
}
else 
{
  statements;
}
statements executed after control;

Switch

A switch compares an expression to multiple case values. Statements within a case execute only if the case value matches the expression value.

Each case can end with an optional break statement which breaks out of the switch control block and continues execution with statements that follow the end of switch.

An optional default statement executes only if none of the case values match the expression value.

If there is no default statement, and no matching case value is found, execution continues with the statement that follows the end of switch.

switch (expression returning a value)
{
case value :
  statements;
break;

case value : 
  statements;
break;
.
.
.

default :
   statements;
}
statements executed after control;