Branching in JavaScript
Branching in JavaScript is very similar to branching in many other languages:
Keyword | Use |
---|---|
if |
introduces the condition and the sequence of steps to execute if the condition is true |
else if |
introduces an alternative condition and the sequence of steps to execute if that condition is true |
else |
introduces the sequence of steps to execute if no other branches have been taken |
We can use if
without else if
or else
; in this case, the statement or statements are executed only if the condition is true, so the two possible courses of action are execute the statement or do nothing. Here and below, notice that the condition is put in parentheses and that a sequence of statements is grouped using braces.
if (condition) statement;
if (condition) {
statement1;
statement2;
}
Another option is to use if
and else
, but not else if
. In this case, there is one condition given. Here there are two courses of action: if the condition is true, statements 1 and 2 are executed, and if it is false, statements 3 and 4 are executed. There can be any number of statements in each branch, and the numbers of statements in different branches need not be the same.
if (condition) {
statement1;
statement2;
} else {
statement3;
statement4;
}
Another option is to introduce multiple conditions, the first using if
, (any number of) subsequent conditions using else if
lines, and ending with a final else
. As above, each branch can have any number of statements.
if (conditionA) {
statement1;
statement2;
} else if (conditionB) {
statement3;
statement4;
} else if (conditionC) {
statement5;
statement6;
} else {
statement7;
statement8;
}
The four possible courses of action are summarized below, indicating which conditions have been checked and whether they are true or false:
conditionA | conditionB | conditionC | Action |
---|---|---|---|
true | not checked | not checked | Statements 1 and 2 are executed |
false | true | not checked | Statements 3 and 4 are executed |
false | false | true | Statements 5 and 6 are executed |
false | false | false | Statements 7 and 8 are executed |