Compound Conditionals
The script that produces the output is slightly more complicated than the previous examples, but still fairly easy to understand.
Try to understand the script source code and then read below for further explanation.
A Compound Conditional works as follows:
if ( boolean expression 1 ) {
JavaScript Statements 1 (will execute if Boolean expression 1 is true)
}
else if ( boolean expression 2 ) {
JavaScript Statements 2 (will execute if Boolean expression 2 is true)
}
else {
JavaScript Statements 3 (will execute if none of the Boolean expressions above are true)
}
The conditional above has 3 conditions including the else clause.
The conditional the actual script for this example has 5 conditions including the else clause, but the smaller one above suffices for explanation.
The Boolean expressions are evaluated starting from the top of the conditional and moving down.
When one Boolean expression evaluates to true, those statements are executed and the rest of the conditional is not even evaluated.
If none of the Boolean expressions are true, then the statements in the else clause execute.
Exactly one one of the statements in the compound conditional will always execute.
The above compound conditional is just a more convenient way to write a nested if/else statement.
The conditional below is exactly equivalent to the one above, just perhaps a little harder to understand.
if ( boolean expression 1 ) {
JavaScript Statements 1 (will execute if Boolean expression 1 is true)
}
else {
if ( boolean expression 2 ) {
JavaScript Statements 2 (will execute if Boolean expression 2 is true)
}
else {
JavaScript Statements 3 (will execute if none of the Boolean expressions above are true)
}
}
An IF statement does not have to have an ELSE clause, and that applies to compound conditionals too.
In the following compound conditional with no ELSE, if neither Boolean expression is true,
none of the JavaScript statements in the conditional will execute.
if ( boolean expression 1 ) {
JavaScript Statements 1 (will execute if Boolean expression 1 is true)
}
else if ( boolean expression 2 ) {
JavaScript Statements 2 (will execute if Boolean expression 2 is true)
}